Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration

Ask Question

I followed few suggestions mentioned here, but it didn't work for me. Hence, putting the question here

  • How To Inject AuthenticationManager using Java Configuration in a Custom Filter
  • Spring required a bean of type 'AuthenticationManager'
  • Could anyone please guide me what's the issue and how to fixed that ?

    Error:

    ***************************
    APPLICATION FAILED TO START
    ***************************
    Description:
    Field authenticationManager in com.techprimers.security.springsecurityauthserver.config.AuthorizationServerConfig required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
    Action:
    Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
    

    AuthorizationServerConfig.java

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
        @Autowired
        private AuthenticationManager authenticationManager;
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()");
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                    .inMemory()
                    .withClient("ClientId")
                    .secret("secret")
                    .authorizedGrantTypes("authorization_code")
                    .scopes("user_info")
                    .autoApprove(true);
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager);
    

    ResourceServerConfig.java

    @EnableResourceServer
    @Configuration
    public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;
        @Autowired
        private UserDetailsService customUserDetailsService;
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatchers()
                    .antMatchers("/login", "/oauth/authorize")
                    .and()
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated()
                    .and()
                    .formLogin()
                    .permitAll();
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.parentAuthenticationManager(authenticationManager)
                    .userDetailsService(customUserDetailsService);
    

    The code reference taken from https://github.com/TechPrimers/spring-security-oauth-mysql-example, only updated Spring Boot Parent Version to 2.0.4.RELEASE, things started breaking.

    It seems like it's one of the "breaking changes" Spring Boot 2.0 introduced. I believe that your case is described in Spring Boot 2.0 Migration Guide.

    In your WebSecurityConfigurerAdapter class you need to override authenticationManagerBean method and annotate it with @Bean, i.e.:

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
                    Please remove the .parentAuthenticationManager(authenticationManagerBean()) part from the example because it causes an error! I just found out that this was the cause of an infinite recursion which eventually leads to a StackOverflowException. The infinite recursion happens whenever AuthenticationManager.authenticate() is called with an incorrect password. This throws BadCredentialsException which causes the same method to be called again for some reason. This most likely happens because the parentAuthenticationManager and the AuthenticationManager are the same instance.
    – Maurice
                    Jan 14, 2022 at 22:31
                    @Maurice thank you for your comment. I admit the second part of my answer was a bit unfortunate and not really necessary. I removed it.
    – Poger
                    Jul 15, 2022 at 8:45
                    Note: In Spring Security 5.x, WebSecurityConfigurerAdapter  is @Deprecated in favor of WebSecurityCustomizer and/or SecurityFilterChain.
    – Ondra Žižka
                    Nov 10, 2022 at 14:49
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    and in your controller where you need to use it add this :
     @Autowired
        private AuthenticationManager authenticationManager;
    

    As WebSecurityConfigurerAdapter it has been deprecated, you can now use:

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .build();
    

    You may want to consider to register a GlobalAuthenticationConfigurerAdapter to configure the AuthenticationManager

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfiguration {
        @Bean
        public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
            final List<GlobalAuthenticationConfigurerAdapter> configurers = new ArrayList<>();
            configurers.add(new GlobalAuthenticationConfigurerAdapter() {
                        @Override
                        public void configure(AuthenticationManagerBuilder auth) throws Exception {
                            // auth.doSomething()
            return authConfig.getAuthenticationManager();
    

    where I assumed for instance that you want to register a custom UserDetailsService (i.e. MyUserDetailsService) and a custom password encoder (MyPasswordEncoder).

    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center. – Community Jun 15, 2022 at 1:57

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.