当前位置:   article > 正文

springSecurity实现验证码_springsecurity验证码验证

springsecurity验证码验证

添加验证码大致可以分为三个步骤:根据随机数生成验证码图片;将验证码图片显示到登录页面;认证流程中加入验证码校验。Spring Security的认证校验是由UsernamePasswordAuthenticationFilter过滤器完成的,所以我们的验证码校验逻辑应该在这个过滤器之前。

生成图形验证码

验证码功能需要用到以下依赖:

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-captcha</artifactId>
  4. <version>5.3.10</version>
  5. </dependency>

这个工具类的用户可以参见该工具的官方文档

接着定义一个ValidateCodeController,用于处理生成验证码请求:

  1. @Configuration
  2. public class KaptchaConfig {
  3. @Bean
  4. public DefaultKaptcha producer() {
  5. DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
  6. Properties properties=new Properties();
  7. //是否有边框
  8. properties.setProperty(Constants.KAPTCHA_BORDER,"yes");
  9. //验证码文本颜色
  10. properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR,"blue");
  11. //验证码图片宽度
  12. properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH,"160");
  13. //验证码图片高度
  14. properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT,"60");
  15. //文本字符大小
  16. properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE,"38");
  17. //验证码session的值
  18. properties.setProperty(Constants.KAPTCHA_SESSION_CONFIG_KEY,"kaptchaCode");
  19. //验证码文本长度
  20. properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH,"4");
  21. //字体
  22. properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体,楷体,微软雅黑");
  23. Config config = new Config(properties);
  24. defaultKaptcha.setConfig(config);
  25. return defaultKaptcha;
  26. }
  27. }
  1. @Slf4j
  2. @RestController
  3. public class ValidateController {
  4. public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
  5. @GetMapping("/code/image")
  6. public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
  7. //设置response响应
  8. response.setCharacterEncoding("UTF-8");
  9. response.setHeader("Pragma", "No-cache");
  10. response.setHeader("Cache-Control", "no-cache");
  11. response.setDateHeader("Expires", 0);
  12. response.setContentType("image/jpeg");
  13. //定义图形验证码的长、宽、验证码字符数、干扰元素个数
  14. CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(100, 38, 4, 20);
  15. System.out.println(captcha.getCode());
  16. //将验证码放到HttpSession里面
  17. request.getSession().setAttribute(SESSION_KEY_IMAGE_CODE, captcha.getCode());
  18. log.info("本次生成的验证码为:" + captcha.getCode() + ",已存放到HttpSession中");
  19. //图形验证码写出,可以写出到文件,也可以写出到流
  20. //输出浏览器
  21. OutputStream out=response.getOutputStream();
  22. captcha.write(out);
  23. out.flush();
  24. out.close();
  25. }
  26. //下面使用redis存储code
  27. @Autowired
  28. Producer producer;
  29. @Autowired
  30. RedisUtil redisUtil;
  31. @PostMapping("/getcaptcha")
  32. @ApiOperation("获取验证码图片")
  33. public R<Map<String,String>> getcaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
  34. response.setContentType("image/png");
  35. String code = producer.createText();
  36. String key = UUID.randomUUID().toString();
  37. BufferedImage image = producer.createImage(code);
  38. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  39. ImageIO.write(image, "jpg", outputStream);
  40. //BASE64Encoder encoder = new BASE64Encoder();解码错误
  41. String str = "data:image/jpeg;base64,";
  42. byte[] bytes= Base64.encodeBase64(outputStream.toByteArray());
  43. String base64 = new String(bytes);
  44. // 存储到redis中
  45. redisUtil.hset("yzm", key, code, 120);
  46. log.info("验证码 -- {} - {}", key, code);
  47. Map<String,String> map=new HashMap<>();
  48. map.put("base64",str+base64);
  49. map.put("key",key);
  50. return R.ok(map);
  51. }
  52. }

使用hutool的CaptchaUtil.createCircleCaptcha方法生成验证码对象,将生成的验证码对象存储到Session中,并通过IO流将生成的图片输出到登录页面上。

改造登录页

在登录页面加上如下代码:

  1. <span style="display: inline">
  2. <input type="text" name="imageCode" placeholder="验证码" style="width: 50%;"/>
  3. <img src="/code/image"/>
  4. </span>
  5. <img>

标签的src属性对应ValidateController的createCode方法。

要使生成验证码的请求不被拦截,需要在SecurityConfig的configure方法中配置免拦截:

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. ...
  4. .antMatchers("/code/image").permitAll() // 无需认证的请求路径
  5. .anyRequest() // 所有请求
  6. ...
  7. }

重启项目,访问http://localhost:8080/loginPage

认证流程添加验证码校验

在校验验证码的过程中,可能会抛出各种验证码类型的异常,比如“验证码错误”、“验证码已过期”等,所以我们定义一个验证码类型的异常类:

  1. public class ValidateCodeException extends AuthenticationException {
  2. private static final long serialVersionUID = 5022575393500654458L;
  3. ValidateCodeException(String message) {
  4. super(message);
  5. }

}
注意,这里继承的是AuthenticationException而不是Exception。

我们都知道,Spring Security实际上是由许多过滤器组成的过滤器链,处理用户登录逻辑的过滤器为UsernamePasswordAuthenticationFilter,而验证码校验过程应该是在这个过滤器之前的,即只有验证码校验通过后采去校验用户名和密码。由于Spring Security并没有直接提供验证码校验相关的过滤器接口,所以我们需要自己定义一个验证码校验的过滤器ValidateCodeFilter:

  1. @Component
  2. public class ValidateCodeFilter extends OncePerRequestFilter {
  3. @Autowired
  4. private AuthenticationFailureHandler authenticationFailureHandler;
  5. @Override
  6. protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
  7. if ("/form".equalsIgnoreCase(httpServletRequest.getRequestURI())
  8. && "post".equalsIgnoreCase(httpServletRequest.getMethod())) {
  9. try {
  10. HttpSession session = httpServletRequest.getSession();
  11. String codeInReq = httpServletRequest.getParameter("imageCode");
  12. validateCode(session,codeInReq);
  13. } catch (ValidateCodeException e) {
  14. authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
  15. return;
  16. }
  17. }
  18. filterChain.doFilter(httpServletRequest, httpServletResponse);
  19. }
  20. private void validateCode(HttpSession session,String codeInRequest) throws ServletRequestBindingException {
  21. String codeInSession = (String)session.getAttribute(ValidateController.SESSION_KEY_IMAGE_CODE);
  22. if (StringUtils.isBlank(codeInRequest)) {
  23. throw new ValidateCodeException("验证码不能为空!");
  24. }
  25. if (codeInSession == null) {
  26. throw new ValidateCodeException("验证码不存在!");
  27. }
  28. if (!codeInRequest.equalsIgnoreCase(codeInSession)) {
  29. throw new ValidateCodeException("验证码不正确!");
  30. }
  31. session.removeAttribute(ValidateController.SESSION_KEY_IMAGE_CODE);
  32. }
  33. }

ValidateCodeFilter继承了org.springframework.web.filter.OncePerRequestFilter,该过滤器只会执行一次。

在doFilterInternal方法中我们判断了请求URL是否为/form,该路径对应登录form表单的action路径,请求的方法是否为POST,是的话进行验证码校验逻辑,否则直接执行filterChain.doFilter让代码往下走。当在验证码校验的过程中捕获到异常时,调用Spring Security的校验失败处理器AuthenticationFailureHandler进行处理。

validateCode的校验逻辑是validateCode方法

我们分别从Session中获取了ImageCode对象和请求参数imageCode(对应登录页面的验证码<input>框name属性),然后进行了各种判断并抛出相应的异常。当验证码过期或者验证码校验通过时,我们便可以删除Session中的ImageCode属性了。

验证码校验过滤器定义好了,怎么才能将其添加到UsernamePasswordAuthenticationFilter前面呢?很简单,只需要在SecurityConfig的configure方法中添加些许配置即可:

  1. @Autowired
  2. private ValidateCodeFilter validateCodeFilter;
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
  6. .formLogin() // 表单登录
  7. // http.httpBasic() // HTTP Basic
  8. .loginPage("/authentication/require") // 登录跳转 URL
  9. .loginProcessingUrl("/login") // 处理表单登录 URL
  10. .successHandler(authenticationSucessHandler) // 处理登录成功
  11. .failureHandler(authenticationFailureHandler) // 处理登录失败
  12. .and()
  13. .authorizeRequests() // 授权配置
  14. .antMatchers("/authentication/require",
  15. "/login.html",
  16. "/code/image").permitAll() // 无需认证的请求路径
  17. .anyRequest() // 所有请求
  18. .authenticated() // 都需要认证
  19. .and().csrf().disable();
  20. }

上面代码中,我们注入了ValidateCodeFilter,然后通过addFilterBefore方法将ValidateCodeFilter验证码校验过滤器添加到了UsernamePasswordAuthenticationFilter前面。

大功告成,重启项目,访问http://localhost:8080/loginPage,当不输入验证码时点击登录,
当输入错误的验证码时点击登录,
 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/741940
推荐阅读
相关标签
  

闽ICP备14008679号