SpringBoot集成SpringSecurity(六)实现登录验证码

该博客介绍了如何在SpringBoot应用中结合SpringSecurity实现登录验证码功能。通过使用hutool插件创建图片验证码并存储在session中,然后自定义验证码过滤器VerifyCodeFilter,该过滤器在UsernamePasswordAuthenticationFilter之前进行验证码校验。当验证码错误时,由自定义的MyLoginFailureHandler处理异常。最后配置过滤器使验证码验证生效,确保在登录过程中验证码的正确性。
摘要由CSDN通过智能技术生成

登录验证码

有很多种实现形式,如自定义类UsernamePasswordAuthenticationFilter(默认的用户认证过滤器)、在UsernamePasswordAuthenticationFilter前添加验证码拦截器等。

下面通过第二种实现,在UsernamePasswordAuthenticationFilter前添加验证码拦截器,如果验证码不通过,那么不继续后面的认证。

验证码实现接口

通过hutool插件实现图片验证码,并将验证码写入到session中,key为verifycode,后面校验时需要从session的key中获取验证码真实内容。

@RequestMapping("/getver")
@ResponseBody
public void verifycode(HttpServletResponse response, HttpSession session) {
    LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 30, 4, 0);
    session.setAttribute("verifycode", captcha.getCode());
    System.out.println(session);
    System.out.println(captcha.getCode());
    SecurityContextHolder.clearContext();
    try {
        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (IOExcept
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值