I have got a working custom Spring Security Configuration, to secure certain url patterns using a JSON Web Token instead of a HTTPSession.
I order to enable method based security in opposite to url based patterns, I need to register an AuthenticationManager, which fails due to a cyclic dependency:
Caused by: 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.
My own dependency is to a filter which I need in order to configure it. Everything works fine, when I omit the registration of the AuthenticationManager:
@Configuration
@EnableWebSecurity
@Order(2)
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private StatelessAuthenticationFilter statelessAuthenticationFilter;
    public SpringSecurityConfig() {
        super(true);
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        ...
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                ...
                // check specific paths for specific role
                .antMatchers("/...").hasRole("...")
                ...
                // all other calls must be authenticated
                .anyRequest().authenticated().and()
                // custom filter to parse JWT token previously sent to client from header and create Authentication
                .addFilterBefore(statelessAuthenticationFilter, (Class<? extends Filter>) UsernamePasswordAuthenticationFilter.class)
                ...
    }
    // config works fine without this method, but method security needs an AuthenticationManager:
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
What am I missing?
Just returning the AuthenticationManager like shown below fixed the problem:
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return authenticationManager();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With