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

如何用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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Security自定义短信验证码登录,需要遵循以下步骤: 1. 配置短信验证码的过滤器 在Spring Security的配置类中,添加一个短信验证码过滤器,用于拦截短信验证码登录请求,并校验验证码是否正确。可以参考以下代码: ``` @Bean public SmsCodeFilter smsCodeFilter() throws Exception { SmsCodeFilter smsCodeFilter = new SmsCodeFilter(); smsCodeFilter.setAuthenticationManager(authenticationManagerBean()); smsCodeFilter.setAuthenticationFailureHandler(authenticationFailureHandler()); return smsCodeFilter; } ``` 2. 实现短信验证码的校验逻辑 创建一个实现了`AuthenticationProvider`接口的短信验证码认证提供者,并在其中实现短信验证码的校验逻辑。可以参考以下代码: ``` @Component public class SmsCodeAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; String mobile = (String) authenticationToken.getPrincipal(); String smsCode = (String) authenticationToken.getCredentials(); // 校验短信验证码 if (smsCodeIsValid(mobile, smsCode)) { // 构造认证通过的令牌 SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(mobile); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } else { throw new BadCredentialsException("短信验证码不正确"); } } private boolean smsCodeIsValid(String mobile, String smsCode) { // 根据手机号和短信验证码进行校验 // ... return true; } @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } } ``` 3. 配置AuthenticationManager 在Spring Security的配置类中,配置`AuthenticationManager`,并将自定义的短信验证码认证提供者加入到其中。可以参考以下代码: ``` @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(smsCodeAuthenticationProvider()); } ``` 4. 配置登录接口 在Spring Security的配置类中,配置短信验证码登录的登录接口。可以参考以下代码: ``` @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(smsCodeFilter(), UsernamePasswordAuthenticationFilter.class) .authorizeRequests() .antMatchers("/sms-login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .and() .csrf().disable(); } ``` 5. 发送短信验证码 在登录接口中,添加发送短信验证码的逻辑。可以参考以下代码: ``` @PostMapping("/sms-code") @ResponseBody public String sendSmsCode(@RequestParam String mobile) { // 发送短信验证码 // ... return "success"; } ``` 以上就是Spring Security自定义短信验证码登录的实现步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值