Describe the bug I'm overriding the authenticationManager method from the WebSecurityConfigurerAdapter in order to create its bean, howerver whenever I try to turn the spring context up (in a test annotated with a @SpringBootTest for example), I get either a StackOverflowError or OutOfMemoryError. I tracked this error to the authenticationManager method, because whenever I remove the @Bean annotation the error disappears.

I'm using gradle, Java 11 and spring-boot-starter-security version 2.5.6

To Reproduce 1. Override the authenticationManager from the WebSecurityConfigurerAdapter class and add a Bean annotation 2. Try to run a test annotated with SpringBootTest

@EnableWebSecurity
@Configuration
public class SecurityConfigurations extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
    ...

Expected behavior Being able to run the app and inject the authenticationManager bean

Sample https://github.com/mmorillodev/stackoverflow-error-sample

Comment From: sjohnr

@mmorillodev, thanks for the report and sample.

I don't believe overriding authenticationManager() is the correct thing to do. Using your sample, I was able to override authenticationManagerBean() instead. However, it will yield a different error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManagerBean' defined in class path resource [com/stackoverflow/playground/config/SecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManagerBean' threw exception; nested exception is org.springframework.beans.FatalBeanException: A dependency cycle was detected when trying to resolve the AuthenticationManager. Please ensure you have configured authentication.

See this comment for some workarounds.

Since we are currently moving away from WebSecurityConfigurerAdapter, the workarounds above are likely your best bet. I'm going to close this issue as a duplicate of #8369. Let me know if you're still having issues after trying the workaround and we can re-open if needed.

Comment From: wigiwee

this might work

@Bean
public AuthenticationManager authenticationManager(
        AuthenticationManagerBuilder authenticationManagerBuilder) {
    return authenticationManagerBuilder.getOrBuild();
}

Comment From: rwinch

To elaborate on what @sjohnr said WebSecurityConfigurerAdapter was removed in Spring Security 6.0.0-RC1 in gh-10902 so this will not happen on supported versions of Spring Security.