Search code examples
springspring-bootspring-securityjwt

Why AuthenticationManager is throwing StackOverflowError?


I am getting StackOverflowError while calling authenticationManger.authenticate()

java.lang.StackOverflowError: null at org.apache.commons.logging.LogAdapter$Slf4jLog.isDebugEnabled(LogAdapter.java:300) ~[spring-jcl-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:162) ~[spring-security-core-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:503) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.6.RELEASE]

I am trying to implement JWT in my application. I have created JWTTOkenUtil, Filter, Controller. But only Authentication manager is not working. I have tried with CustomAuthenticationManger as well but same error.

File AppConfig.java

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class AppConfig  extends WebSecurityConfigurerAdapter{

    @Autowired
    private JwtUserDetailService jwtUserDetailService;

    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(jwtAuthenticationProvider);

     //auth.userDetailsService(jwtUserDetailService).passwordEncoder(passwordEncoder());
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests().antMatchers("/version").permitAll()
            .anyRequest().authenticated()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public JwtRequestFilter jwtRequestFilter() {
            return new JwtRequestFilter();
    }
}

Solution

  • authenticationManager() and authenticationManagerBean() of WebSecurityConfigurerAdapter are two different methods, and you are calling authenticationManagerBean() method of your super class, which, as far as I know, depends on authenticationManager() method. This, in return creates a cyclic calls of methods, which finally results in StackOverflowError exception.

    You could try just not override AuthenticationManager authenticationManager() method, or return a solid implementation when doing so.