赞
踩
添加验证码大致可以分为三个步骤:根据随机数生成验证码图片;将验证码图片显示到登录页面;认证流程中加入验证码校验。Spring Security的认证校验是由UsernamePasswordAuthenticationFilter过滤器完成的,所以我们的验证码校验逻辑应该在这个过滤器之前。
验证码功能需要用到以下依赖:
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-captcha</artifactId>
- <version>5.3.10</version>
- </dependency>
这个工具类的用户可以参见该工具的官方文档
接着定义一个ValidateCodeController,用于处理生成验证码请求:
- @Configuration
- public class KaptchaConfig {
- @Bean
- public DefaultKaptcha producer() {
- DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
- Properties properties=new Properties();
- //是否有边框
- properties.setProperty(Constants.KAPTCHA_BORDER,"yes");
- //验证码文本颜色
- properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR,"blue");
- //验证码图片宽度
- properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH,"160");
- //验证码图片高度
- properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT,"60");
- //文本字符大小
- properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE,"38");
- //验证码session的值
- properties.setProperty(Constants.KAPTCHA_SESSION_CONFIG_KEY,"kaptchaCode");
- //验证码文本长度
- properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH,"4");
- //字体
- properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体,楷体,微软雅黑");
-
- Config config = new Config(properties);
- defaultKaptcha.setConfig(config);
- return defaultKaptcha;
-
- }
- }

- @Slf4j
- @RestController
- public class ValidateController {
-
- public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
-
- @GetMapping("/code/image")
- public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
- //设置response响应
- response.setCharacterEncoding("UTF-8");
- response.setHeader("Pragma", "No-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
- response.setContentType("image/jpeg");
-
- //定义图形验证码的长、宽、验证码字符数、干扰元素个数
- CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(100, 38, 4, 20);
- System.out.println(captcha.getCode());
- //将验证码放到HttpSession里面
- request.getSession().setAttribute(SESSION_KEY_IMAGE_CODE, captcha.getCode());
- log.info("本次生成的验证码为:" + captcha.getCode() + ",已存放到HttpSession中");
-
- //图形验证码写出,可以写出到文件,也可以写出到流
- //输出浏览器
- OutputStream out=response.getOutputStream();
- captcha.write(out);
- out.flush();
- out.close();
-
- }
-
- //下面使用redis存储code
- @Autowired
- Producer producer;
- @Autowired
- RedisUtil redisUtil;
- @PostMapping("/getcaptcha")
- @ApiOperation("获取验证码图片")
- public R<Map<String,String>> getcaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setContentType("image/png");
- String code = producer.createText();
- String key = UUID.randomUUID().toString();
- BufferedImage image = producer.createImage(code);
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- ImageIO.write(image, "jpg", outputStream);
- //BASE64Encoder encoder = new BASE64Encoder();解码错误
- String str = "data:image/jpeg;base64,";
- byte[] bytes= Base64.encodeBase64(outputStream.toByteArray());
- String base64 = new String(bytes);
- // 存储到redis中
- redisUtil.hset("yzm", key, code, 120);
- log.info("验证码 -- {} - {}", key, code);
- Map<String,String> map=new HashMap<>();
- map.put("base64",str+base64);
- map.put("key",key);
- return R.ok(map);
- }
- }

使用hutool的CaptchaUtil.createCircleCaptcha方法生成验证码对象,将生成的验证码对象存储到Session中,并通过IO流将生成的图片输出到登录页面上。
在登录页面加上如下代码:
- <span style="display: inline">
- <input type="text" name="imageCode" placeholder="验证码" style="width: 50%;"/>
- <img src="/code/image"/>
- </span>
- <img>
标签的src属性对应ValidateController的createCode方法。
要使生成验证码的请求不被拦截,需要在SecurityConfig的configure方法中配置免拦截:
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- ...
- .antMatchers("/code/image").permitAll() // 无需认证的请求路径
- .anyRequest() // 所有请求
- ...
- }
重启项目,访问http://localhost:8080/loginPage
在校验验证码的过程中,可能会抛出各种验证码类型的异常,比如“验证码错误”、“验证码已过期”等,所以我们定义一个验证码类型的异常类:
- public class ValidateCodeException extends AuthenticationException {
- private static final long serialVersionUID = 5022575393500654458L;
- ValidateCodeException(String message) {
- super(message);
- }
}
注意,这里继承的是AuthenticationException而不是Exception。
我们都知道,Spring Security实际上是由许多过滤器组成的过滤器链,处理用户登录逻辑的过滤器为UsernamePasswordAuthenticationFilter,而验证码校验过程应该是在这个过滤器之前的,即只有验证码校验通过后采去校验用户名和密码。由于Spring Security并没有直接提供验证码校验相关的过滤器接口,所以我们需要自己定义一个验证码校验的过滤器ValidateCodeFilter:
- @Component
- public class ValidateCodeFilter extends OncePerRequestFilter {
-
- @Autowired
- private AuthenticationFailureHandler authenticationFailureHandler;
-
- @Override
- protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
- if ("/form".equalsIgnoreCase(httpServletRequest.getRequestURI())
- && "post".equalsIgnoreCase(httpServletRequest.getMethod())) {
- try {
- HttpSession session = httpServletRequest.getSession();
- String codeInReq = httpServletRequest.getParameter("imageCode");
- validateCode(session,codeInReq);
- } catch (ValidateCodeException e) {
- authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
- return;
- }
- }
- filterChain.doFilter(httpServletRequest, httpServletResponse);
- }
-
- private void validateCode(HttpSession session,String codeInRequest) throws ServletRequestBindingException {
- String codeInSession = (String)session.getAttribute(ValidateController.SESSION_KEY_IMAGE_CODE);
-
- if (StringUtils.isBlank(codeInRequest)) {
- throw new ValidateCodeException("验证码不能为空!");
- }
- if (codeInSession == null) {
- throw new ValidateCodeException("验证码不存在!");
- }
- if (!codeInRequest.equalsIgnoreCase(codeInSession)) {
- throw new ValidateCodeException("验证码不正确!");
- }
- session.removeAttribute(ValidateController.SESSION_KEY_IMAGE_CODE);
-
- }
-
- }
-

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方法中添加些许配置即可:
- @Autowired
- private ValidateCodeFilter validateCodeFilter;
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
- .formLogin() // 表单登录
- // http.httpBasic() // HTTP Basic
- .loginPage("/authentication/require") // 登录跳转 URL
- .loginProcessingUrl("/login") // 处理表单登录 URL
- .successHandler(authenticationSucessHandler) // 处理登录成功
- .failureHandler(authenticationFailureHandler) // 处理登录失败
- .and()
- .authorizeRequests() // 授权配置
- .antMatchers("/authentication/require",
- "/login.html",
- "/code/image").permitAll() // 无需认证的请求路径
- .anyRequest() // 所有请求
- .authenticated() // 都需要认证
- .and().csrf().disable();
- }

上面代码中,我们注入了ValidateCodeFilter,然后通过addFilterBefore方法将ValidateCodeFilter验证码校验过滤器添加到了UsernamePasswordAuthenticationFilter前面。
大功告成,重启项目,访问http://localhost:8080/loginPage,当不输入验证码时点击登录,
当输入错误的验证码时点击登录,
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。