Spring Boot版本:3.1.2
目前我实现了一个简单的基于Spring Boot的应用程序,其中涉及Spring Security,如下所示。 但是,当我尝试使用表单登录时,我收到“找不到 org.springframework.security.authentication.UsernamePasswordAuthenticationToken 的 AuthenticationProvider”。
问题:为什么会出现这样的错误?我认为默认情况下,DaoAuthenticationProvider 将由 Spring Boot 实例化,它将自动选取我们配置的任何自定义 UserDetailsService bean 和 PasswordEncoder bean。
注意:如果我在错误的论坛上发帖,请告诉我。
@Configuration
public class DemoSecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
var encoders = new HashMap<String, PasswordEncoder>(
Map.of("bcrypt",new BCryptPasswordEncoder(),
"noop", NoOpPasswordEncoder.getInstance())
);
var e = new DelegatingPasswordEncoder("noop", encoders);
return e;
}
@Bean
public UserDetailsService userDetailsManager() {
UserDetails susan = User.builder()
.username("susan")
.password("{noop}test123")
.roles("EMPLOYEE", "MANAGER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(susan);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(configurer ->
configurer.requestMatchers("/css/**").permitAll()
.anyRequest().authenticated()
);
http.formLogin(Customizer.withDefaults());
http.csrf(csrf -> csrf.disable());
return http.build();
}
}
`
我找到了根本原因。
如果您创建自己的UserDetailsService bean,则无需手动为AuthenticationProvider定义bean,因为Spring boot会自动为我们创建一个DaoAuthenticationProvider,它将自动拾取您定义的UserDetailsService bean。
但是如果你定义了2个或更多UserDetailsService bean,那么你需要定义你自己的Authenticationprovider。我犯了一个错误,因为我没有意识到我有另一个实现 UserDetailsService 接口并用 @Service 注释的类,它创建了第二个 UserDetailsService bean。