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();
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/193429.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • centos7设置go代理

    centos7设置go代理wgethttps://dl.google.com/go/go1.10.3.linux-amd64.tar.gztar-C/usr/local-zxvfgo1.10.3.linux-amd64.tar.gzvim/etc/profileexportGOROOT=/usr/local/goexportPATH=$PATH:$GOROOT/binexportGOPROXY=https://goproxy.cnsource/etc/profilegoversion..

  • 二叉树前序遍历详解[通俗易懂]

    二叉树前序遍历详解[通俗易懂]二叉树的遍历是数据结构中非常基础的内容了,今天这一篇文章我们来详细了解一下二叉树的前序遍历,二叉树的前序遍历顺序是根节点-左子树-右子树,本文对递归和栈模拟的方法都有实现一、递归方法递归方法可以说是很简了,我们秉承先去往左节点再去往右节点的原则就好了//assumethatwehaveTreeNode,andresistostoretheanswervoidpreorder(TreeNode*root,vector<int&.

  • 极限思想之芝诺悖论[通俗易懂]

    极限思想之芝诺悖论[通俗易懂]芝诺悖论是古希腊哲学家芝诺提出的一组悖论。芝诺是一个很有学问,同时也很好玩的人(淘气)。他如果在中国出生,估计很难大学毕业,只能跟池子(脱口秀演员~)一样,高中教室门外面站三年课,然后去讲脱口秀糊口。阿基里斯,大家都知道。古希腊神话中的战神。无论是力量,速度,耐力,格斗技巧,都是巅峰级别的。一夜睡三女,第二天依然可以血染特洛伊的男人。芝诺就提出:在跑步比赛中,如果跑得最慢的乌龟一开始领先…

  • Pycharm连接mysql数据库报错1130,1054「建议收藏」

    Pycharm连接mysql数据库报错1130,1054「建议收藏」Pycharm连接mysql报错1130,1054

  • linux手动安装gcc-5.1.0「建议收藏」

    linux手动安装gcc-5.1.0「建议收藏」yum源和apt-get源安装linux下安装gcc和g++时,可以使用源安装,例如:yuminstallgcc或者apt-getinstallgcc,但是这有个缺点,就是可能不能安装到你想要的版本,因此我们需要手动安装。下载gcc不同版本gcc是gnu的产品,所以我们可以去gnu官网去下,但是gnu下载的比减慢,这里提供一些大学的软件开元镜像源,比如清华大学:清华大学开元镜像源…

  • 解析PHP的self关键字

    解析PHP的self关键字

发表回复

您的电子邮箱地址不会被公开。

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