一: 生成验证码

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

  1. <dependency>
  2. <groupId>org.springframework.social</groupId>
  3. <artifactId>spring-social-config</artifactId>
  4. <version>1.1.4.RELEASE</version>
  5. </dependency>

创建图片验证码对象

  1. package com.springboot.securityone.utils;
  2. import java.awt.image.BufferedImage;
  3. import java.time.LocalDateTime;
  4. /**
  5. * <p>
  6. * Description:[]
  7. * </p>
  8. *
  9. * @author shf
  10. * @version 1.0
  11. * @date Created on 2020/4/30 16:52
  12. */
  13. public class ImageCode {
  14. private BufferedImage image;
  15. private String code;
  16. private LocalDateTime expireTime;
  17. public ImageCode(BufferedImage image, String code, int expireIn) {
  18. this.image = image;
  19. this.code = code;
  20. this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
  21. }
  22. public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
  23. this.image = image;
  24. this.code = code;
  25. this.expireTime = expireTime;
  26. }
  27. boolean isExpire() {
  28. return LocalDateTime.now().isAfter(expireTime);
  29. }
  30. public BufferedImage getImage() {
  31. return image;
  32. }
  33. public void setImage(BufferedImage image) {
  34. this.image = image;
  35. }
  36. public String getCode() {
  37. return code;
  38. }
  39. public void setCode(String code) {
  40. this.code = code;
  41. }
  42. public LocalDateTime getExpireTime() {
  43. return expireTime;
  44. }
  45. public void setExpireTime(LocalDateTime expireTime) {
  46. this.expireTime = expireTime;
  47. }
  48. }

新增获取验证码的 controller

  1. package com.springboot.securityone.controller;
  2. import com.springboot.securityone.utils.ImageCode;
  3. import org.springframework.social.connect.web.HttpSessionSessionStrategy;
  4. import org.springframework.social.connect.web.SessionStrategy;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import org.springframework.web.context.request.ServletWebRequest;
  8. import javax.imageio.ImageIO;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.awt.*;
  12. import java.awt.image.BufferedImage;
  13. import java.io.IOException;
  14. import java.util.Random;
  15. /**
  16. * <p>
  17. * Description:[]
  18. * </p>
  19. *
  20. * @author shf
  21. * @version 1.0
  22. * @date Created on 2020/4/30 16:53
  23. */
  24. @RestController
  25. public class ValidateController {
  26. public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
  27. private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
  28. @GetMapping("/code/image")
  29. public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
  30. ImageCode imageCode = createImageCode();
  31. sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode);
  32. ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());
  33. }
  34. /**
  35. * 功能描述: <br>
  36. * 〈生成验证码〉
  37. * @Param:
  38. * @Return:
  39. * @Author: shihengfei
  40. * @Date: 2020/4/30 16:59
  41. */
  42. private ImageCode createImageCode() {
  43. int width = 100; // 验证码图片宽度
  44. int height = 36; // 验证码图片长度
  45. int length = 4; // 验证码位数
  46. int expireIn = 60; // 验证码有效时间 60s
  47. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  48. Graphics g = image.getGraphics();
  49. Random random = new Random();
  50. g.setColor(getRandColor(200, 250));
  51. g.fillRect(0, 0, width, height);
  52. g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
  53. g.setColor(getRandColor(160, 200));
  54. for (int i = 0; i < 155; i++) {
  55. int x = random.nextInt(width);
  56. int y = random.nextInt(height);
  57. int xl = random.nextInt(12);
  58. int yl = random.nextInt(12);
  59. g.drawLine(x, y, x + xl, y + yl);
  60. }
  61. StringBuilder sRand = new StringBuilder();
  62. for (int i = 0; i < length; i++) {
  63. String rand = String.valueOf(random.nextInt(10));
  64. sRand.append(rand);
  65. g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
  66. g.drawString(rand, 13 * i + 6, 16);
  67. }
  68. g.dispose();
  69. return new ImageCode(image, sRand.toString(), expireIn);
  70. }
  71. private Color getRandColor(int fc, int bc) {
  72. Random random = new Random();
  73. if (fc > 255) {
  74. fc = 255;
  75. }
  76. if (bc > 255) {
  77. bc = 255;
  78. }
  79. int r = fc + random.nextInt(bc - fc);
  80. int g = fc + random.nextInt(bc - fc);
  81. int b = fc + random.nextInt(bc - fc);
  82. return new Color(r, g, b);
  83. }
  84. }

二:登录页面新增验证码:

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

因为 code/image 接口需要无权限访问,配置放开:

  1. .antMatchers("/login.html","/code/image").permitAll()

三:登录流程添加验证码校验

1. 定义验证码异常处理类

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

  1. import org.springframework.security.core.AuthenticationException;
  2. /**
  3. * <p>
  4. * Description:[验证码校验异常]
  5. * </p>
  6. *
  7. * @author shf
  8. * @version 1.0
  9. * @date Created on 2020/4/30 17:11
  10. */
  11. public class ValidateCodeException extends AuthenticationException {
  12. private static final long serialVersionUID = 5022575393500654458L;
  13. ValidateCodeException(String message) {
  14. super(message);
  15. }
  16. }

2. 定义验证码验证过滤器

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

  1. package com.springboot.securityone.filter;
  2. import com.springboot.securityone.exception.ValidateCodeException;
  3. import org.apache.commons.lang3.StringUtils;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  6. import org.springframework.social.connect.web.HttpSessionSessionStrategy;
  7. import org.springframework.social.connect.web.SessionStrategy;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.web.bind.ServletRequestBindingException;
  10. import org.springframework.web.context.request.ServletWebRequest;
  11. import org.springframework.web.filter.OncePerRequestFilter;
  12. import javax.servlet.FilterChain;
  13. import javax.servlet.ServletException;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.IOException;
  17. /**
  18. * <p>
  19. * Description:[验证码过滤器]
  20. * </p>
  21. *
  22. * @author shf
  23. * @version 1.0
  24. * @date Created on 2020/4/30 17:14
  25. */
  26. @Component
  27. public class ValidateCodeFilter extends OncePerRequestFilter {
  28. @Autowired
  29. private AuthenticationFailureHandler authenticationFailureHandler;
  30. private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
  31. @Override
  32. protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
  33. FilterChain filterChain) throws ServletException, IOException {
  34. if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI())
  35. && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
  36. try {
  37. validateCode(new ServletWebRequest(httpServletRequest));
  38. } catch (ValidateCodeException e) {
  39. authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
  40. return;
  41. }
  42. }
  43. filterChain.doFilter(httpServletRequest, httpServletResponse);
  44. }
  45. /**
  46. * 功能描述: <br>
  47. * 〈校验验证码〉
  48. * @Param:
  49. * @Return:
  50. * @Author: shihengfei
  51. * @Date: 2020/4/30 17:16
  52. */
  53. private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
  54. // 校验
  55. }
  56. }

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

3. validateCode的校验逻辑

  1. private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
  2. // 校验
  3. ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
  4. String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");
  5. if (StringUtils.isBlank(codeInRequest)) {
  6. throw new ValidateCodeException("验证码不能为空!");
  7. }
  8. if (codeInSession == null) {
  9. throw new ValidateCodeException("验证码不存在!");
  10. }
  11. if (codeInSession.isExpire()) {
  12. sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
  13. throw new ValidateCodeException("验证码已过期!");
  14. }
  15. if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
  16. throw new ValidateCodeException("验证码不正确!");
  17. }
  18. sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
  19. }

从 SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); 中获取验证码信息。校验。

4.添加过滤器到 UsernamePasswordAuthenticationFilter 过滤器之前。

配置文件新增:

  1. @Autowired
  2. private ValidateCodeFilter validateCodeFilter;
  3. ......
  4. http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
  5. .formLogin()

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