当前位置:   article > 正文

SpringSecurity整合图形验证码_spring security 滑块验证码

spring security 滑块验证码

SpringSecurity简单整合SpringBoot

在上一篇的博客中,教大家如何简单的整合SpringSecurity并使用,但是很多小伙伴都说,“哎呀,你这个只输入了用户名和密码,我还想加一个图形验证码怎么办”。我想想也是,实际的业务场景当中可能还存在图形验证码的校验以及图形滑块的校验等,所以这篇博客就来讲讲SpringSecurity整合图形验证码

1、生成图形验证码

我们知道前端的图片显示图形验证码只需要在它的src属性中指定对应的请求路径即可,并且我们点击图片的时候还能刷新图形验证码,所以可以写一个简单的接口,这里直接引用做完的图形验证码的依赖(偷懒一下)

  1. <dependency>
  2.     <groupId>com.github.whvcse</groupId>
  3.     <artifactId>easy-captcha</artifactId>
  4.     <version>1.6.2</version>
  5. </dependency>

该依赖里面有很多的图形验证码,这里我直接使用最简单的数字验证码了,生成之后我们有两种方式存储我们的验证码,第一种是存储到服务端的session当中,第二种是存放到Redis缓存当中,两种皆可,这里都给大家演示一下

方法一:存储到session当中

  1. @RequestMapping("/captcha")
  2. public void captcha(HttpServletRequest request, HttpServletResponse response){
  3.     //获取验证码
  4.     response.setContentType("image/jpg");
  5.     response.setHeader("Pargam","No-cache");
  6.     response.setHeader("cache-Control","no-cache");
  7.     response.setDateHeader("Expires",0);
  8.     //生成对应的验证码
  9.     ArithmeticCaptcha captch = new ArithmeticCaptcha(110383);
  10.     //将验证码存入到session当中,并且设置session的过期时间为3分钟
  11.     request.getSession().setMaxInactiveInterval(3*60);
  12.     request.getSession().setAttribute("captcha",captch.text());
  13.     try {
  14.         //将生成的验证码输出到前端
  15.         captch.out(response.getOutputStream());
  16.     } catch (IOException e) {
  17.         //验证码生成失败就记录到日志当中
  18.         log.error("验证码生成失败",e.getMessage());
  19.     }
  20. }

方法二:存储到Redis缓存当中

注:存储到Redis缓存当中的时候,我们不能直接存储,因为Session是不能被不同客户端所共享的,而Redis可以被不同客户端所共享,所以在存储到Redis当中的时候可以根据用户的ip地址进行存储,这样不同客户端就不会产生冲突(使用Redis时还需要更改配置文件)

  1. @Autowired
  2. @Qualifier("MyRedisTemplate")
  3. private RedisTemplate redisTemplate;
  4. @RequestMapping("/captcha")
  5. public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
  6.     //获取验证码
  7.     response.setContentType("image/jpg");
  8.     response.setHeader("Pargam","No-cache");
  9.     response.setHeader("cache-Control","no-cache");
  10.     response.setDateHeader("Expires",0);
  11.     //生成验证码,将验证码放入redis当中
  12.     ArithmeticCaptcha captch = new ArithmeticCaptcha(110383);
  13.     //获得用户的ip地址
  14.     String ip = getIpAddress(request);
  15.     //将验证码存储到缓存当中,有效时间为5分钟
  16.     redisTemplate.opsForValue().set("captcha:"+ip,captch.text(),300, TimeUnit.SECONDS);
  17.     try {
  18.         captch.out(response.getOutputStream());
  19.     } catch (IOException e) {
  20.         log.error("验证码生成失败",e.getMessage());
  21.     }
  22. }
  23. //获取客户端IP地址
  24. public String getIpAddress(HttpServletRequest request) {
  25.     String ip = request.getHeader("x-forwarded-for");
  26.     if(ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
  27.         ip = request.getHeader("Proxy-Client-IP");
  28.     }
  29.     if (ip == null || ip.length () == 0 || "unknown".equalsIgnoreCase (ip)) {
  30.         ip = request.getHeader ("WL-Proxy-Client-IP");
  31.     }
  32.     if (ip == null || ip.length () == 0 || "unknown".equalsIgnoreCase (ip)) {
  33.         ip = request.getRemoteAddr ();
  34.         if (ip.equals ("127.0.0.1")) {
  35.             //根据网卡取本机配置的IP
  36.             InetAddress inet = null;
  37.             try {
  38.                 inet = InetAddress.getLocalHost ();
  39.             } catch (Exception e) {
  40.                 e.printStackTrace ();
  41.             }
  42.             ip = inet.getHostAddress ();
  43.         }
  44.     }
  45.     // 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  46.     if (ip != null && ip.length () > 15) {
  47.         if (ip.indexOf (",") > 0) {
  48.             ip = ip.substring (0, ip.indexOf (","));
  49.         }
  50.     }
  51.     return ip;
  52. }

2、自定义图形验证码过滤器

那验证码存储完之后,我们怎么在进行用户名和密码判断之前先去判断输入的验证码是否正确呢,这个时候我们可以继承UsernamePasswordAuthenticationFilter这个类,然后实现对应的方法,这个类是AbstractAuthenticationProcessingFilter针对使用用户名和密码进行身份验证而定制化的一个过滤器,所以我们可以在里面对我们输入的验证码进行判断(判断方法根据之前存储验证码的方式来)

  1. //用Session进行判断
  2. public class LoginFilter extends UsernamePasswordAuthenticationFilter {
  3.     @Override
  4.     public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  5.         if (!request.getMethod().equals("POST")) {
  6.             throw new AuthenticationServiceException(
  7.                     "Authentication method not supported: " + request.getMethod());
  8.         }
  9.         //获取到服务端的验证码session
  10.         String captcha = (String) request.getSession().getAttribute("captcha");
  11.         //如果验证码为空,说明对应的session信息已经过期了
  12.         if(captcha==null){
  13.             throw new AuthenticationServiceException("验证码已过期");
  14.         }
  15.         //获取前端输入的验证码,判断是否一致
  16.         String kaptcha = request.getParameter("captcha");
  17.         if (!StringUtils.isEmpty(kaptcha) && !StringUtils.isEmpty(captcha) && kaptcha.equalsIgnoreCase(captcha)) {
  18.             //如果一致的话,就通过了我们的验证码认证,继续执行登录逻辑
  19.             return super.attemptAuthentication(request, response);
  20.         }
  21.         throw new AuthenticationServiceException("验证码输入错误");
  22.     }
  23. }
  24. //用Redis进行判断
  25. public class LoginFilter extends UsernamePasswordAuthenticationFilter {
  26.     @Autowired
  27.     @Qualifier("MyRedisTemplate")
  28.     private RedisTemplate redisTemplate;
  29.     
  30.     @Autowired
  31.     private UserController userController;
  32.     @Override
  33.     public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  34.         if (!request.getMethod().equals("POST")) {
  35.             throw new AuthenticationServiceException(
  36.                     "Authentication method not supported: " + request.getMethod());
  37.         }
  38.         //获取用户的ip
  39.         String ip = userController.getIpAddress(request);
  40.         //根据用户的ip来获取对应的缓存验证码
  41.         String captcha = (String) redisTemplate.opsForValue().get("captcha:" + ip);
  42.         //如果缓存不存在,就说明缓存有可能过期了
  43.         if(captcha==null){
  44.             throw new AuthenticationServiceException("验证码已过期");
  45.         }
  46.         //获取前端输入的验证码,判断是否一致
  47.         String kaptcha = request.getParameter("captcha");
  48.         if (!StringUtils.isEmpty(kaptcha) && !StringUtils.isEmpty(captcha) && kaptcha.equalsIgnoreCase(captcha)) {
  49.             return super.attemptAuthentication(request, response);
  50.         }
  51.         throw new AuthenticationServiceException("验证码输入错误");
  52.     }
  53. }

3、注入自定义过滤器

定义好我们的验证码过滤器之后,我们就需要在我们的配置类当中引入一下

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3.     //把自定义的过滤器添加到UsernamePasswordAuthenticationFilter前去
  4.     http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
  5. }
  6. @Override
  7. @Bean
  8. public AuthenticationManager authenticationManagerBean()
  9.         throws Exception {
  10.     return super.authenticationManagerBean();
  11. }
  12. @Bean
  13. LoginFilter loginFilter() throws Exception {
  14.     LoginFilter loginFilter = new LoginFilter();
  15.     loginFilter.setFilterProcessesUrl("/login");
  16.     loginFilter.setAuthenticationManager(authenticationManagerBean());
  17.     //登录成功后的跳转
  18.     loginFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/"));
  19.     //登录失败后的跳转
  20.     loginFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/toLogin?error=true"));
  21.     return loginFilter;
  22. }

我们还需要在我们的前端页面中加入验证码的输入框,name根据我们的要求进行指定

  1. //显示对应的错误信息
  2. <p style="color: red;" th:if="${param.error}" th:text="${session['SPRING_SECURITY_LAST_EXCEPTION'].message}"></p>
  3. <form action="/login" method="post">
  4.     用户名:<input type="text" name="username"><br>
  5.     密码:<input type="password" name="password"><br>
  6.     验证码:<input type="text" name="captcha"><img style="width: 110px;height: 38px" src="/captcha"><br>
  7.     <input type="checkbox" name="rememberMe">记住我<br>
  8.     <input type="submit" value="登录">
  9. </form>

4、效果查看

完成之后我们就可以启动项目进行测试了,我们可以先输入错误的验证码来查看效果,然后还可以等待验证码过期然后进行效果的查看

  • 验证码过期效果

  • 验证码错误效果

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

闽ICP备14008679号