添加验证码大致可以分为三个步骤:根据随机数生成验证码图片;将验证码图片显示到登录页面;认证流程中加入验证码校验。Spring Security的认证校验是由UsernamePasswordAuthenticationFilter过滤器完成的,所以我们的验证码校验逻辑应该在这个过滤器之前。下面一起学习下如何在上一节Spring Security自定义用户认证的基础上加入图片验证码校验功能。

生成图形验证码

验证码功能需要用到spring-social-config依赖:

 <dependency><groupId>org.springframework.social</groupId><artifactId>spring-social-config</artifactId>
</dependency>

首先定义一个验证码对象ImageCode:

public class ImageCode {private BufferedImage image;private String code;private LocalDateTime expireTime;public ImageCode(BufferedImage image, String code, int expireIn) {this.image = image;this.code = code;this.expireTime = LocalDateTime.now().plusSeconds(expireIn);}public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {this.image = image;this.code = code;this.expireTime = expireTime;}public boolean isExpire() {return LocalDateTime.now().isAfter(expireTime);}// get,set 略
}

ImageCode对象包含了三个属性:image图片,code验证码和expireTime过期时间。isExpire方法用于判断验证码是否已过期。

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

@RestController
public class ValidateController {public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();@GetMapping("/code/image")public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {ImageCode imageCode = createImageCode();sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode);ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());}
}

createImageCode方法用于生成验证码对象,org.springframework.social.connect.web.HttpSessionSessionStrategy对象封装了一些处理Session的方法,包含了setAttributegetAttributeremoveAttribute方法,具体可以查看该类的源码。使用sessionStrategy将生成的验证码对象存储到Session中,并通过IO流将生成的图片输出到登录页面上。

其中createImageCode方法代码如下所示:

private ImageCode createImageCode() {int width = 100; // 验证码图片宽度int height = 36; // 验证码图片长度int length = 4; // 验证码位数int expireIn = 60; // 验证码有效时间 60sBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = image.getGraphics();Random random = new Random();g.setColor(getRandColor(200, 250));g.fillRect(0, 0, width, height);g.setFont(new Font("Times New Roman", Font.ITALIC, 20));g.setColor(getRandColor(160, 200));for (int i = 0; i < 155; i++) {int x = random.nextInt(width);int y = random.nextInt(height);int xl = random.nextInt(12);int yl = random.nextInt(12);g.drawLine(x, y, x + xl, y + yl);}StringBuilder sRand = new StringBuilder();for (int i = 0; i < length; i++) {String rand = String.valueOf(random.nextInt(10));sRand.append(rand);g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));g.drawString(rand, 13 * i + 6, 16);}g.dispose();return new ImageCode(image, sRand.toString(), expireIn);
}private Color getRandColor(int fc, int bc) {Random random = new Random();if (fc > 255) {fc = 255;}if (bc > 255) {bc = 255;}int r = fc + random.nextInt(bc - fc);int g = fc + random.nextInt(bc - fc);int b = fc + random.nextInt(bc - fc);return new Color(r, g, b);
}

生成验证码的方法写好后,接下来开始改造登录页面。

改造登录页

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

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

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

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

@Override
protected void configure(HttpSecurity http) throws Exception {http.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();
}

重启项目,访问http://localhost:8080/login.html,效果如下:

认证流程添加验证码校验

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

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 {@Autowiredprivate AuthenticationFailureHandler authenticationFailureHandler;private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();@Overrideprotected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI())&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {try {validateCode(new ServletWebRequest(httpServletRequest));} catch (ValidateCodeException e) {authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);return;}}filterChain.doFilter(httpServletRequest, httpServletResponse);}private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {...} }

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

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

validateCode的校验逻辑如下所示:

private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");if (StringUtils.isBlank(codeInRequest)) {throw new ValidateCodeException("验证码不能为空!");}if (codeInSession == null) {throw new ValidateCodeException("验证码不存在!");}if (codeInSession.isExpire()) {sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);throw new ValidateCodeException("验证码已过期!");}if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {throw new ValidateCodeException("验证码不正确!");}sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);}

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

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

@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/login.html,

  • 当不输入验证码时点击登录,页面显示如下:

  • 当输入错误的验证码时点击登录,页面显示如下:

  • 当页面加载60秒后再输入验证码点击登录,页面显示如下:

当验证码通过,并且用户名密码正确时,页面显示如下:

源码链接 :https://github.com/AndyYoungCN/Spring-Security/tree/master/ss-validatecode

备注

该工程只是一个介绍性的demo,不能用户正式环境中。因为在这里只保留了验证码的结果,不适合多用户。现在项目大部分为前后端分离,缓存验证码建议使用redis等缓存而不是session

4.Spring Security 添加图形验证码相关推荐

  1. Spring Security添加图形验证码

    Spring Security添加图形验证码 大致思路: 1.根据随机数生成验证码图片 2.将验证码图片显示到登录页面 3.认证流程中加入验证码校验 依赖 <dependency>< ...

  2. 9.Spring Security添加记住我功能

    在网站的登录页面中,记住我选项是一个很常见的功能,勾选记住我后在一段时间内,用户无需进行登录操作就可以访问系统资源.在Spring Security中添加记住我功能很简单,大致过程是:当用户勾选了记住 ...

  3. 5.Spring Security 短信验证码登录

    Spring Security 短信验证码登录 在 Spring Security 添加图形验证码一节中,我们已经实现了基于 Spring Boot + Spring Security 的账号密码登录 ...

  4. Spring Security 短信验证码登录(5)

    在Spring Security添加图形验证码中,我们已经实现了基于Spring Boot + Spring Security的账号密码登录,并集成了图形验证码功能.时下另一种非常常见的网站登录方式为 ...

  5. SpringSecurity添加图形验证码认证功能

    SpringSecurity添加图形验证码认证功能 第一步:图形验证码接口 1.使用第三方的验证码生成工具Kaptcha https://github.com/penggle/kaptcha @Con ...

  6. spring security 短信验证码登录

    短信登录过滤器  SmsAuthenticationFilter  import org.springframework.lang.Nullable; import org.springframewo ...

  7. Spring boot+ Spring security 实现图片验证码验证

    springboot+security实现用户权限管理后,登陆要求增加图片验证码 pring security使用众多的过滤器对url进行拦截,以此来进行权限管理.Spring security不允许 ...

  8. 使用Spring Security添加RememberMe身份验证

    我在" 将社交登录添加到Jiwhiz博客"中提到,RememberMe功能不适用于Spring Social Security. 好吧,这是因为该应用程序现在不通过用户名和密码对用 ...

  9. vue添加图形验证码功能

    上图看功能,每点击一次切换验证码!前端判断验证码是否输入,后端判断验证码是否正确! html <el-form-item label="验证码" prop="cod ...

最新文章

  1. python 线程安全链表_教你用 Python 实现 HashMap 数据结构
  2. 深度学习:dropout和BN的实现
  3. 对ios中CGContextRef和image的处理
  4. 陶陶摘苹果(洛谷-P1046)
  5. es6 为什么修饰器不能用于函数
  6. 2017.2.27自测
  7. linux空间满了有什么问题,Linux 空间满问题分析 [ Keep Coding ]
  8. vs binsum
  9. Android 桌面组件【widget】初探
  10. jzoj2941. 贿赂
  11. wps文档服务器授权怎么解,如何解决WPS提示授权已到期的问题
  12. java代码处理URL转码
  13. 钓鱼邮件检测(本科毕设)
  14. 以太坊智能合约开发语言 - Solidity
  15. scrapy实战--爬取腾讯的招聘信息
  16. html实现下拉跳转
  17. 莫纳什大学计算机专业排名,2019上海软科世界一流学科排名计算机科学与工程专业排名莫纳什大学排名第151-200...
  18. Android Studio与Mysql连接的中文乱码问题
  19. Integer对象的大小比较
  20. 【计算机网络】超详细——华为eNSP的安装教程

热门文章

  1. linux 极简统计分析工具 datamash 必看教程
  2. 微生物组:3分和30分文章差距在哪里?
  3. 扩增子分析QIIME. 3以管理员安装QIIME1.9.1至Ubuntu16.04
  4. Python seaborn可视化:组合多个seaborn可视化结果并使得组合结果图像共享X轴、使用matplotlib的subplots子图函数的gridspec_kw参数指定子图的相对大小或者比率
  5. seaborn箱图(box plot)可视化、并且使用matplotlib的meanprops函数在箱图中自定义均值标签、标签形状、标签大小、标签填充色彩、标签边缘颜色
  6. 分类模型的ROC曲线、AUC值、GINI系数、Lift、Gain、KS指标分别是什么?计算公式是什么?有什么意义?
  7. R语言gc函数垃圾回收实战
  8. R语言apropos函数查找包含特定字符的函数、find函数查找函数所在的位置实战
  9. R假设检验之k-s检验(KOLMOGOROV AND SMIRNOV TEST)
  10. 使用python包faker生成仿真数据