在验证用户名和密码之前,引入辅助验证可有效防范暴力试错,图形验证码就是简单且行有效的一种辅助验证方式。下面将使用过滤器和自定义认证两种方式实现图形验证码功能。
验证码(CAPTCHA)的全称是Completely Automated Public Turing test to tell Computers and Humans Apart,翻译过来就是“全自动区分计算机和人类的图灵测试”。通俗地讲,验证码就是为了防止恶意用户暴力重试而设置的。不管是用户注册、用户登录,还是论坛发帖,如果不加以限制,一旦某些恶意用户利用计算机发起无限重试,就很容易使系统遭受破坏。
1.自定义过滤器
在Spring Security中,实现验证码校验的方式有很多种,最简单的方式就是自定义一个专门处理验证码逻辑的过滤器,将其添加到Spring Security过滤器链的合适位置。当匹配到登录请求时,立刻对验证码进行校验,成功则放行,失败则提前结束整个验证请求。
说到Spring Security的过滤器,我们先回顾一下前面使用过的配置。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/api/**").hasRole("ADMIN")
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.formLogin()
.and()
.sessionManagement()
.maximumSessions(1);
}
}
HttpSecurity实际上就是在配置Spring Security的过滤器链,诸如CSRF、CORS、表单登录等,每个配置器对应一个过滤器。我们可以通过 HttpSecurity 配置过滤器的行为,甚至可以像CRSF一样直接关闭过滤器。例如,SessionManagement。
public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws Exception {
return getOrApply(new SessionManagementConfigurer<>());
}
Spring Security通过SessionManagementConfigurer来配置SessionManagement的行为。与 SessionManagementConfigurer 类似的配置器还有 CorsConfigurer、RememberMeConfigurer 等,它们都实现了SecurityConfigurer的标准接口。
public interface SecurityConfigurer<O, B extends SecurityBuilder<O>> {
// 各个配置器初始化的方法
void init(B builder) throws Exception;
// 各个配置器被统一调用的方法
void configure(B builder) throws Exception;
}
SessionManagementConfigurer是在configure方法中将最终的SessionManagementFilte