SpringSecurity添加图形验证码认证实现

作者:卑微小钟 时间:2023-07-08 01:37:52 

第一步:图形验证码接口

1.使用第三方的验证码生成工具Kaptcha

https://github.com/penggle/kaptcha

@Configuration
public class KaptchaImageCodeConfig {
   @Bean
   public DefaultKaptcha getDefaultKaptcha(){
       DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
       Properties properties = new Properties();
       properties.setProperty(Constants.KAPTCHA_BORDER, "yes");
       properties.setProperty(Constants.KAPTCHA_BORDER_COLOR, "192,192,192");
       properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, "110");
       properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, "36");
       properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
       properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "28");
       properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体");
       properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
       // 图片效果
       properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL,
               "com.google.code.kaptcha.impl.ShadowGimpy");
       Config config = new Config(properties);
       defaultKaptcha.setConfig(config);
       return defaultKaptcha;
   }
}

2.设置验证接口

Logger logger = LoggerFactory.getLogger(getClass());
public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
@GetMapping("/code/image")
public void codeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
   // 获得随机验证码
   String code = defaultKaptcha.createText();
   logger.info("验证码:{}",code);
   // 将验证码存入session
   request.getSession().setAttribute(SESSION_KEY,code);
   // 绘制验证码
   BufferedImage image = defaultKaptcha.createImage(code);
   // 输出验证码
   ServletOutputStream out = response.getOutputStream();
   ImageIO.write(image, "jpg", out);
}

3.模板表单设置

<div class="form-group">
   <label>验证码:</label>
   <input type="text" class="form-control" placeholder="验证码" name="code">
   <img src="/code/image" th:src="@{/code/image}" onclick="this.src='/code/image?'+Math.random()">
</div>

第二步:设置图像验证过滤器

1.过滤器


@Component
public class ImageCodeValidateFilter extends OncePerRequestFilter {
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    // 失败处理器
    @Resource
    public void setMyAuthenticationFailureHandler(MyAuthenticationFailureHandler myAuthenticationFailureHandler) {
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            if ("/login/form".equals(request.getRequestURI()) &&
                    request.getMethod().equalsIgnoreCase("post")) {
                // 获取session的验证码
                String sessionCode = (String) request.getSession().getAttribute(PageController.SESSION_KEY);
                // 获取用户输入的验证码
                String inputCode = request.getParameter("code");
                // 判断是否正确
                if(sessionCode == null||!sessionCode.equals(inputCode)){
                    throw new ValidateCodeException("验证码错误");
                }
            }
        }catch (AuthenticationException e){
            myAuthenticationFailureHandler.onAuthenticationFailure(request,response,e);
            //e.printStackTrace();
            return;
        }
        filterChain.doFilter(request, response);
    }
}

异常类

public class ValidateCodeException extends AuthenticationException {
   public ValidateCodeException(String msg) {
       super(msg);
   }
}

注意:一定是继承AuthenticationException

第三步:将图像验证过滤器添加到springsecurity过滤器链中

1.添加到过滤器链中,并设置在用户认证过滤器(UsernamePasswordAuthenticationFilter)前

@Resource
private ImageCodeValidateFilter imageCodeValidateFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
   // 前后代码略
   // 添加图形验证码过滤器链
   http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
}

2.一定不要忘记放行验证码接口

// 拦截设置
http
   .authorizeHttpRequests()
   //排除/login
   .antMatchers("/login","/code/image").permitAll();

来源:https://blog.csdn.net/zhongjianboy/article/details/123942771

标签:SpringSecurity,图形,验证码
0
投稿

猜你喜欢

  • Java虚拟机内存结构及编码实战分享

    2023-11-29 13:47:47
  • Android编程之消息机制实例分析

    2023-07-28 07:24:38
  • Java实现生成JSON字符串的三种方式分享

    2022-05-20 15:21:31
  • Java获取接口所有实现类的方式详解

    2022-06-11 14:44:27
  • spring web.xml指定配置文件过程解析

    2023-05-15 01:32:40
  • IntelliJ IDEA Run时报“无效的源发行版:16“错误问题及解决方法

    2022-06-04 18:08:35
  • IntelliJ IDEA 好用插件之analyze inspect code详解

    2021-09-26 22:16:36
  • C#使用远程服务调用框架Apache Thrift

    2023-05-07 01:05:01
  • C# 图片与Base64码的相互转化问题(代码详解)

    2021-11-30 22:56:16
  • C# 设计模式系列教程-模板方法模式

    2022-03-17 18:00:15
  • Android Flutter实现仿闲鱼动画效果

    2023-07-15 15:32:47
  • 深入了解Java数据结构和算法之堆

    2022-07-23 19:45:49
  • C# Winform消息通知系统托盘气泡提示框ToolTip控件

    2023-01-13 23:31:02
  • C#使用TimeSpan时间计算的简单实现

    2023-10-06 07:25:55
  • Android 消息分发使用EventBus的实例详解

    2022-12-23 06:28:28
  • Java设计模式之GOF23全面讲解

    2023-06-24 06:15:06
  • C#使用BinaryFormatter类、ISerializable接口、XmlSerializer类进行序列化和反序列化

    2023-01-16 02:11:54
  • Java定时器问题实例解析

    2021-08-21 21:02:53
  • Flutter路由传递参数及解析实现

    2023-06-22 11:48:45
  • 详解Java中字符流与字节流的区别

    2023-01-14 00:19:58
  • asp之家 软件编程 m.aspxhome.com