参考https://www.baeldung.com/spring-security-extra-login-fields
我打算自定义 Spring security Authentication UsernamePasswordAuthenticationFilter 的功能来获取额外的自定义“loginForm”字段。
我创建了一个自定义过滤器
CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter
Run Code Online (Sandbox Code Playgroud)
和一个定制的身份验证令牌
public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken
Run Code Online (Sandbox Code Playgroud)
通过使用以下配置:
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class AuthenticationSecurityConfig extends AbstractHttpConfigurer<AuthenticationSecurityConfig, HttpSecurity> {
@Override
public void configure(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
http.addFilterBefore(authenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class);
}
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers("/css/**", "/login")
.permitAll()
.requestMatchers("/resources/**")
.permitAll()
.and()
.formLogin(form -> form
.loginPage("/login")
.permitAll()
)
.logout()
.logoutUrl("/logout")
.and()
.authorizeHttpRequests(
auth -> auth.anyRequest().authenticated()
)
.apply(securityConfig());
return http.build();
}
}
Run Code Online (Sandbox Code Playgroud)
我可以成功创建我的 AuthenticationProvider …