Spring Security - 实现图形验证码(一)

Spring Security - 使用过滤器实现图形验证码

实现思路就是在校验用户名和密码前加上一层过滤,验证码校验,通过请求获取图形验证码,请求成功的同时将验证码明文信息保存在session中,用于后面的校验,校验成功后走后面的逻辑。

一、准备配置

为工程引用依赖


    cloud.agileframework
    spring-boot-starter-kaptcha
    2.0.0

配置一个kaptcha实例

WebSecurityConfig里添加

@Bean
public Producer kaptcha() {
    //配置图形验证码的基本参数
    Properties properties = new Properties();
    //图片宽度
    properties.setProperty("kaptcha.image.width", "150");
    //图片长度
    properties.setProperty("kaptcha.image.height", "50");
    //字符集
    properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
    //字符长度
    properties.setProperty("kaptcha.textproducer.char.length", "4");
    Config config = new Config(properties);
    //使用默认的图形验证码实现,也可以自定义
    DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
    defaultKaptcha.setConfig(config);
    return defaultKaptcha;
}

创建一个CaptchaControlle用于获取图形验证码

@Controller
public class CaptchaController {

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha.jpg")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置内容类型
        response.setContentType("image/jpeg");
        //创建验证码文本
        String capText = captchaProducer.createText();
        //将验证码文本设置到session
        request.getSession().setAttribute("captcha", capText);
        //创建验证码图片
        BufferedImage capImage = captchaProducer.createImage(capText);
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将图片验证码数据写到响应输出流
        ImageIO.write(capImage, "jpg", outputStream);
        //推送并关闭响应输出流
        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    }

}

二、自定义图形验证码校验过滤器

通过继承OncePerRequestFilter来实现,它可以保证一次请求只通过一次该过滤器

1. 自定义校验异常类

创建异常包exception

继承AuthenticationException

/**
 * 验证码校验失败异常
 */
public class VerificationCodeException extends AuthenticationException {
    public VerificationCodeException(String msg) {
        super(msg);
    }
}

2. 自定义异常处理handler

创建处理器包handler

实现AuthenticationFailureHandler

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(401);
        PrintWriter out = httpServletResponse.getWriter();
        out.write("{\n" +
                "    \"error_code\": 401,\n" +
                "    \"error_name\":" + "\"" + e.getClass().getName() + "\",\n" +
                "    \"message\": \"请求失败," + e.getMessage() + "\"\n" +
                "}");
    }
}

3. 自定义校验验证码过滤器

创建过滤器包filter

继承OncePerRequestFilter

public class VerificationCodeFilter extends OncePerRequestFilter {

    private final AuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //非登录请求不校验验证码
        String requestURI = httpServletRequest.getRequestURI();
        if (!"/myLogin".equalsIgnoreCase(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            try {
                verificationCode(httpServletRequest);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } catch (VerificationCodeException e) {
                System.out.println(e);
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }

    private void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException {
        String captcha = httpServletRequest.getParameter("captcha");
        HttpSession session = httpServletRequest.getSession();
        String captchaCode = (String) session.getAttribute("captcha");
        if (StringUtils.isNotEmpty(captchaCode)) {
            // 校验过一次后清除验证码,不管成功或失败
            session.removeAttribute("captcha");
        }
        //校验不通过抛出异常
        if (StringUtils.isEmpty(captcha) || StringUtils.isEmpty(captchaCode) || !captcha.equals(captchaCode))
            throw new VerificationCodeException("图形验证码校验异常");
    }
}

4. 修改配置configure

  • 放行请求验证码api/captcha.jpg
  • 添加验证失败处理
  • 将过滤器添加在UsernamePasswordAuthenticationFilter之前
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**","/captcha.jpg").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/myLogin.html")
                // 指定处理登录请求的路径,修改请求的路径,默认为/login
                .loginProcessingUrl("/mylogin").permitAll()
                .failureHandler(new MyAuthenticationFailureHandler())
                .and()
                .csrf().disable();
        //将过滤器添加在UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }

三、修改登录页面

在之前的基础上修改页面,添加验证码输入框




    
    
    
    登录


密码登录
请输入登录账户和密码

四、测试

启动项目

访问api:http://localhost:8080/user/api/hi

image-20201019160019522.png

输入正确用户名密码,正确验证码

访问成功

页面显示hi,user.

重启项目

输入正确用户名密码,错误验证码

访问失败

返回失败报文

{
"error_code": 401,
"error_name": "com.yang.springsecurity.exception.VerificationCodeException",
"message": "请求失败,图形验证码校验异常"
}

你可能感兴趣的:(Spring Security - 实现图形验证码(一))