Spring Security 如何添加登录验证码?松哥手把手教你给微人事添加登录验证码

登录添加验证码是一个非常常见的需求,网上也有非常成熟的解决方案。在传统的登录流程中加入一个登录验证码也不是难事,但是如何在 Spring Security 中添加登录验证码,对于初学者来说还是一件蛮有挑战的事情,因为默认情况下,在 Spring Security 中我们并不需要自己写登录认证逻辑,只需要自己稍微配置一下就可以了,所以如果要添加登录验证码,就涉及到如何在 Spring Security 即有的认证体系中,加入自己的验证逻辑。

学习本文,需要大家对 Spring Security 的基本操作有一些了解,如果大家对于 Spring Security 的操作还不太熟悉,可以在公众号后台回复 springboot,获取松哥纯手敲的 274 页免费 Spring Boot 学习干货。

好了,那么接下来,我们就来看下我是如何通过自定义过滤器给微人事添加上登录验证码的。

【手把手视频教程链接】

好了,不知道小伙伴们有没有看懂呢?视频中涉及到的所有代码我已经提交到 GitHub 上了:https://github.com/lenve/vhr。如果小伙伴们对完整的微人事视频教程感兴趣,可以点击这里:Spring Boot + Vue 视频教程喜迎大结局,西交大的老师竟然都要来一套!

最后,还有一个去年写的关于验证码的笔记,小伙伴们也可以参考下。

准备验证码

要有验证码,首先得先准备好验证码,本文采用 Java 自画的验证码,代码如下:

  1. /** * 生成验证码的工具类 */
  2. public class VerifyCode {
  3. private int width = 100;// 生成验证码图片的宽度
  4. private int height = 50;// 生成验证码图片的高度
  5. private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
  6. private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
  7. private Random random = new Random();
  8. private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  9. private String text;// 记录随机字符串
  10. /** * 获取一个随意颜色 * * @return */
  11. private Color randomColor() {
  12. int red = random.nextInt(150);
  13. int green = random.nextInt(150);
  14. int blue = random.nextInt(150);
  15. return new Color(red, green, blue);
  16. }
  17. /** * 获取一个随机字体 * * @return */
  18. private Font randomFont() {
  19. String name = fontNames[random.nextInt(fontNames.length)];
  20. int style = random.nextInt(4);
  21. int size = random.nextInt(5) + 24;
  22. return new Font(name, style, size);
  23. }
  24. /** * 获取一个随机字符 * * @return */
  25. private char randomChar() {
  26. return codes.charAt(random.nextInt(codes.length()));
  27. }
  28. /** * 创建一个空白的BufferedImage对象 * * @return */
  29. private BufferedImage createImage() {
  30. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  31. Graphics2D g2 = (Graphics2D) image.getGraphics();
  32. g2.setColor(bgColor);// 设置验证码图片的背景颜色
  33. g2.fillRect(0, 0, width, height);
  34. return image;
  35. }
  36. public BufferedImage getImage() {
  37. BufferedImage image = createImage();
  38. Graphics2D g2 = (Graphics2D) image.getGraphics();
  39. StringBuffer sb = new StringBuffer();
  40. for (int i = 0; i < 4; i++) {
  41. String s = randomChar() + "";
  42. sb.append(s);
  43. g2.setColor(randomColor());
  44. g2.setFont(randomFont());
  45. float x = i * width * 1.0f / 4;
  46. g2.drawString(s, x, height - 15);
  47. }
  48. this.text = sb.toString();
  49. drawLine(image);
  50. return image;
  51. }
  52. /** * 绘制干扰线 * * @param image */
  53. private void drawLine(BufferedImage image) {
  54. Graphics2D g2 = (Graphics2D) image.getGraphics();
  55. int num = 5;
  56. for (int i = 0; i < num; i++) {
  57. int x1 = random.nextInt(width);
  58. int y1 = random.nextInt(height);
  59. int x2 = random.nextInt(width);
  60. int y2 = random.nextInt(height);
  61. g2.setColor(randomColor());
  62. g2.setStroke(new BasicStroke(1.5f));
  63. g2.drawLine(x1, y1, x2, y2);
  64. }
  65. }
  66. public String getText() {
  67. return text;
  68. }
  69. public static void output(BufferedImage image, OutputStream out) throws IOException {
  70. ImageIO.write(image, "JPEG", out);
  71. }
  72. }

这个工具类很常见,网上也有很多,就是画一个简单的验证码,通过流将验证码写到前端页面,提供验证码的 Controller 如下:

  1. @RestController
  2. public class VerifyCodeController {
  3. @GetMapping("/vercode")
  4. public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  5. VerifyCode vc = new VerifyCode();
  6. BufferedImage image = vc.getImage();
  7. String text = vc.getText();
  8. HttpSession session = req.getSession();
  9. session.setAttribute("index_code", text);
  10. VerifyCode.output(image, resp.getOutputStream());
  11. }
  12. }

这里创建了一个 VerifyCode 对象,将生成的验证码字符保存到 session 中,然后通过流将图片写到前端,img 标签如下:

  1. <img src="/vercode" alt="">

展示效果如下:

format_png

自定义过滤器

在登陆页展示验证码这个就不需要我多说了,接下来我们来看看如何自定义验证码处理器:

  1. @Component
  2. public class VerifyCodeFilter extends GenericFilterBean {
  3. private String defaultFilterProcessUrl = "/doLogin";
  4. @Override
  5. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
  6. throws IOException, ServletException {
  7. HttpServletRequest request = (HttpServletRequest) req;
  8. HttpServletResponse response = (HttpServletResponse) res;
  9. if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
  10. // 验证码验证
  11. String requestCaptcha = request.getParameter("code");
  12. String genCaptcha = (String) request.getSession().getAttribute("index_code");
  13. if (StringUtils.isEmpty(requestCaptcha))
  14. throw new AuthenticationServiceException("验证码不能为空!");
  15. if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
  16. throw new AuthenticationServiceException("验证码错误!");
  17. }
  18. }
  19. chain.doFilter(request, response);
  20. }
  21. }

自定义过滤器继承自 GenericFilterBean,并实现其中的 doFilter 方法,在 doFilter 方法中,当请求方法是 POST,并且请求地址是 /doLogin 时,获取参数中的 code 字段值,该字段保存了用户从前端页面传来的验证码,然后获取 session 中保存的验证码,如果用户没有传来验证码,则抛出验证码不能为空异常,如果用户传入了验证码,则判断验证码是否正确,如果不正确则抛出异常,否则执行 chain.doFilter(request, response); 使请求继续向下走。

配置

最后在 Spring Security 的配置中,配置过滤器,如下:

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Autowired
  4. VerifyCodeFilter verifyCodeFilter;
  5. ...
  6. ...
  7. @Override
  8. protected void configure(HttpSecurity http) throws Exception {
  9. http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
  10. http.authorizeRequests()
  11. .antMatchers("/admin/**").hasRole("admin")
  12. ...
  13. ...
  14. .permitAll()
  15. .and()
  16. .csrf().disable();
  17. }
  18. }

这里只贴出了部分核心代码,即 http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class); ,如此之后,整个配置就算完成了。

接下来在登录中,就需要传入验证码了,如果不传或者传错,都会抛出异常,例如不传的话,抛出如下异常:

format_png 1

本文案例,我已经上传到 GitHub ,欢迎大家 star:https://github.com/lenve/javaboy-code-samples

好了,本文就先说到这里,有问题欢迎留言讨论。

发表评论

表情:
评论列表 (有 0 条评论,63人围观)

还没有评论,来说两句吧...

相关阅读

    相关 手把手验证检验的登录

    在网站实际应用过程中,为了防止网站登录接口被机器人轻易地使用,产生一些没有意义的用户数据,所以,采用验证码进行一定程度上的拦截,当然,我们采用的还是一个数字与字母结合的图片验证