SpringCloud OAuth2 登录加入图形验证码

该文描述了在SpringBoot应用中生成和验证图形验证码的流程,包括使用CaptchaUtil创建验证码图片,将验证码存储在session中,定义Filter进行验证码校验,以及处理验证失败的情况。同时,文章提到了安全配置,如将验证码接口添加到白名单,并在认证服务中配置过滤规则。当遇到集群环境时,建议将验证码存储在Redis中。
摘要由CSDN通过智能技术生成

一、生成验证码图片

 @GetMapping("getImageVerifyCode")
    public Map<String,Object> getImageVerifyCode(HttpServletRequest request, HttpServletResponse response)throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(155, 45, 5, 4);
        //图形验证码写出,可以写出到文件,也可以写出到流
        String verifyCode = captcha.getCode();
        request.getSession().setAttribute("verifyCode",verifyCode);

        Map<String,Object> map = new HashMap<>(3);
        map.put("data",captcha.getImageBase64Data());
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

当然,网关处得把这个地址加入白名单。

还有认证服务中security配置也加入过滤

.antMatchers("/oauth/getImageVerifyCode").permitAll()

二、定义Filter

/**
 * @author cmy
 * @date 2023/5/6 11:37
 */
@Component
@Setter
public class CaptchaFilter extends OncePerRequestFilter {

    private String processUrl = "/oauth/token";

    AuthenticationFailureHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(processUrl.equals(request.getRequestURI()) && StrUtil.equalsAnyIgnoreCase(request.getMethod(), "post")){
            try {
                validate(request);
            } catch (ValidateCodeException e) {
                failureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) throws ValidateCodeException{
        String imageCodeInSession = request.getSession().getAttribute("verifyCode").toString();
        String imageCode = request.getHeader("imageCode");
        System.out.println("imageCodeInSession = " + imageCodeInSession);
        System.out.println("imageCode = " + imageCode);
        if(StrUtil.isEmpty(imageCodeInSession)){
            throw new ValidateCodeException("验证码不存在,请重新获取");
        }
        if (StrUtil.isEmpty(imageCode)) {
            throw new ValidateCodeException("验证码不能为空,请输入验证码");
        }
        if(!imageCode.equals(imageCodeInSession)){
            throw new ValidateCodeException("验证码不匹配");
        }
        request.getSession().removeAttribute("verifyCode");
    }
}

这边是把验证码放到session里面,目前认证服务没有集群,后期如果集群的话,可以放入Redis

三、定义异常处理

/**
 * @author cmy
 * @date 2023/5/6 11:57
 */
public class ValidateCodeException extends AuthenticationException {
    public ValidateCodeException(String s) {
        super(s);
    }
}

/**
 * @author cmy
 * @date 2023/5/6 12:24
 */
@Component
public class CaptchaAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        Map<String, Object> data = new HashMap<>();
        data.put("data",null);
        data.put("msg", exception.getMessage());
        data.put("code",HttpStatus.BAD_REQUEST.value());

        PrintWriter out = response.getWriter();
        out.write(objectMapper.writeValueAsString(data));
    }
}

四、加入security配置

configure方法中
captchaFilter.setFailureHandler(captchaAuthenticationFailureHandler);

.and().addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值