springsecurity自定义密码验证_数字图形验证码怎么填

springsecurity自定义密码验证_数字图形验证码怎么填SpringSecurity添加图形验证码认证功能第一步:图形验证码接口1.使用第三方的验证码生成工具Kaptchahttps://github.com/penggle/kaptcha@ConfigurationpublicclassKaptchaImageCodeConfig{@BeanpublicDefaultKaptchagetDefaultKaptcha(){DefaultKaptchadefaultKaptcha=newDefa

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

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

第一步:图形验证码接口

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://javaforall.net/193429.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 深入浅出讲解Optional包装类

    深入浅出讲解Optional包装类Optional是JDK8的新特性,首先这个类是被final修饰的,并且这个类只有一个Object的超类,下面是这个类的结构。我们可以看到一共也没多少方法,所以我觉得就从这个类开始,养成阅读源码的习惯,再合适不过了。Optional的作用在写这篇博客之前,看过好多相关的资料,大体上来说这个类就是用来解决万恶的空指针异常,用来避免繁琐的!=null代码而存在的。那你也太…

    2022年9月21日
    1
  • 在JAVA中 System.getProperty 和 System.setProperty 方法.

    在JAVA中 System.getProperty 和 System.setProperty 方法.

    2021年11月30日
    52
  • php curl 请求头、响应头[通俗易懂]

    php curl 请求头、响应头

    2022年2月17日
    54
  • qlineedit自动补全_qlineedit只能输入数字

    qlineedit自动补全_qlineedit只能输入数字转载:http://www.cnblogs.com/csuftzzk/p/qss_lineedit_completer.html?utm_source=tuicool&utm_medium=referral显示密码显示密码时,利用lineedit-password-character属性更改密文显示字符内容。QLineEdit[echoMode=”2″]{lineedit…

    2022年10月5日
    0
  • 微型四旋翼飞行器设计经验之瞎扯淡[通俗易懂]

    在正式开始记录微型四旋翼飞行器设计的学习笔记之前,感觉自己很有必要先给自己一个总结,也希望能够帮到更多的朋友少走弯路(虽然不知道帮助大不大)。去年九月下旬开始了微型四旋翼飞行器的学习与设计,在12月底的时候初步实现了稳定的遥控与飞行,后续又增加了一些常规的辅助的功能,失控保护、姿态微调等等,之后又利用OLED屏幕,设计了一个三级菜单,把各种参数的设置,飞控锁定与通讯的状态等等一些信息都整合在一

    2022年4月10日
    77
  • 教你如何使用 chmod 命令「建议收藏」

    教你如何使用 chmod 命令「建议收藏」chmod是Linux中一个关于权限分配的命令。在具体介绍命令使用之前,先介绍一些基础知识。Linux中对于一个文件的权限有三种:拥有者、群组、其他。分别用u、g和o表示。如果是表示所有人,则可以用a表示。那么对于chmod命令的基本语法结构如下:chmod[-cfvR][ugoa…][+-=][rwxX]下面依次介绍,其具体含义。第一部分[-cfvR]不是必选的,是增强其功能的选择。其中-R使用频率较高。 -c:若该档案权限确实已经更改,才显示其更改动作 -f:

    2022年6月18日
    27

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号