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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 如何计算经纬度之间的距离_根据经纬度算距离

    如何计算经纬度之间的距离_根据经纬度算距离用php计算两个指定的经纬度地点之间的距离,代码:/***求两个已知经纬度之间的距离,单位为米*@paramlng1,lng2经度*@paramlat1,lat2纬度*@returnfloat距离,单位米*@editwww.jbxue.com**/functiongetdistance($lng1,$lat1,$lng2,$lat2){//将角度转为狐度$radLat1=deg2r…

    2022年9月2日
    6
  • java中url加密处理

    java中url加密处理packagetest importjava security Key importjava security SecureRandom importjavax crypto Cipher importjavax crypto KeyGenerator importsun misc BASE64Decode importsun misc BASE64Encode

    2025年7月25日
    2
  • (七十)Android O Service启动流程梳理——bindService

    (七十)Android O Service启动流程梳理——bindService前言:最近在处理anr问题的时候迫切需要搞清楚service的启动流程,抽时间梳理一下。1.service启动简述service启动分三种,比较简单的就是startService,AndroidO用于后台应用启动前台服务的startForegroundService和绑定服务的bindService。本篇继(六十四)AndroidOService启动流程梳理——startService 继续…

    2022年6月4日
    44
  • MMC卡修复心得与方法

    MMC卡修复心得与方法手机内存卡修复1.放存储卡在电脑识别.放到手机不识别!!这种情况往往是因为存储卡在电脑上进行格式化,但是格式化与手机不兼容.解决方法是吧卡放回手机,用手机中的”格式化存储卡”功能从新格式化!!2.手机提示”拔出存储卡,请按确定”按照提示将卡拔出来,一会再插入手机就可以继续使用,但是过不了多久有在回提示拔卡,如此反复!!这是因为经常插拔存储卡,导致手机存储卡槽松动接触不良.

    2022年6月1日
    34
  • m3u8合并解密 TS视频文件分片合并解密

    m3u8合并解密 TS视频文件分片合并解密m3u8合并解密qq群:366950911图片:合并成功

    2022年6月29日
    111
  • pytorch之nn.Conv1d详解

    pytorch之nn.Conv1d详解之前学习pytorch用于文本分类的时候,用到了一维卷积,花了点时间了解其中的原理,看网上也没有详细解释的博客,所以就记录一下。Conv1dclasstorch.nn.Conv1d(in_channels,out_channels,kernel_size,stride=1,padding=0,dilation=1,groups=1,bias=True)in_channe…

    2022年6月12日
    109

发表回复

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

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