如何用Spring Security自定义验证码?

本文指导如何在Spring Security中集成Google验证码,包括依赖导入、配置Kaptcha Servlet路径,以及自定义CheckCaptchaFilter进行验证码校验,并将其添加到Security过滤器链中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何用SpringSecurity自定义验证码?

导入依赖

  • 这里使用Google的验证码
  • 因为Google官方的maven坐标导入不了,使用的是镜像
<dependency>
	<groupId>com.github.penggle</groupId>
	<artifactId>kaptcha</artifactId>
	<version>2.3.2</version>
</dependency>

设置图片验证码路径

  • 谷歌提供了一个默认的Servletcom.google.code.kaptcha.servlet.KaptchaServlet
  • 设置路径
@Configuration
public class ServletConfig {
    @Bean
    public ServletRegistrationBean<KaptchaServlet> servletRegistrationBean() {
        KaptchaServlet kaptchaServlet = new KaptchaServlet();
        return new ServletRegistrationBean<>(kaptchaServlet,"/captcha.jpg");
    }
}

自定义filter

  • 自定义一个filter来校验验证码
@Component
public class CheckCaptchaFilter extends OncePerRequestFilter {

	// 谷歌的默认验证码session key
    private static final String CAPTCAH_SESSION_KEY = Constants.KAPTCHA_SESSION_KEY;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String realRequestUrl = request.getRequestURI().substring(request.getContextPath().length());
        // 不是登录请求,放行
        if (!"/login".equals(realRequestUrl)) {
            filterChain.doFilter(request,response);
            return;
        }
        // 获取默认的 captcha
        String sessionCaptcha = (String) request.getSession().getAttribute(CAPTCAH_SESSION_KEY);
        String captcha = request.getParameter("captcha");
        if (sessionCaptcha == null || captcha == null) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return;
        }
        if(sessionCaptcha.equalsIgnoreCase(captcha)) {
            // 验证码正确,清除验证码session
            request.getSession().removeAttribute(CAPTCAH_SESSION_KEY);
            filterChain.doFilter(request,response);
        } else {
//            throw new RuntimeException("验证码错误");
            response.sendRedirect(request.getContextPath() + "/login.html");
        }

    }

}

Filter添加

  • 把自定义的filter添加到Security的过滤器链中
  • 应当在身份验证过滤器之前UsernamePasswordAuthenticationFilter
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CheckCaptchaFilter checkCaptchaFilter;

     // 省略.....

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       
       // 省略.....

        http.addFilterBefore(checkCaptchaFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值