Spring Security报错:找不到AuthenticationManager类型Bean 求解决
Hey there, let's get that missing AuthenticationManager bean sorted out for your authorization server! The root issue here is that Spring Security doesn't expose the AuthenticationManager as an injectable bean by default—you need to explicitly configure it in your security setup.
Solution 1: Using WebSecurityConfigurerAdapter (Legacy Approach)
If you're using an older version of Spring Security (pre-5.7) or still relying on WebSecurityConfigurerAdapter, create a security configuration class that exposes the AuthenticationManager as a bean:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // Expose AuthenticationManager as a bean for dependency injection @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } // Configure your user authentication (example with in-memory users) @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("your-user") .password("{noop}your-password") // {noop} disables password encoding (only for testing!) .roles("USER"); } }
Once you add this class, your AuthServerConfig will be able to autowire the AuthenticationManager successfully.
Solution 2: Spring Security 5.7+ (Recommended Approach)
If you're using Spring Security 5.7 or later (where WebSecurityConfigurerAdapter is deprecated), use the modern component-based configuration:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .formLogin(form -> form.permitAll()); // Adjust login settings as needed return http.build(); } // Expose AuthenticationManager bean @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager(); } // Example: In-memory user details service @Bean public UserDetailsService userDetailsService() { UserDetails testUser = User.withUsername("test-user") .password("{noop}test-pass") .roles("USER") .build(); return new InMemoryUserDetailsManager(testUser); } }
Quick Checks to Ensure It Works
- Make sure both your
SecurityConfigandAuthServerConfigare in a package that's scanned by Spring (i.e., under your main application class's package or explicitly included in@ComponentScan). - Verify you have the necessary dependencies: If you're using Spring Boot, include
spring-boot-starter-securityin yourpom.xmlorbuild.gradle.
That should resolve the "could not be found" error for the AuthenticationManager bean!
内容的提问来源于stack exchange,提问作者gstackoverflow

