Рассмотрите возможность определения bean-компонента типа org.springframework.security.authentication.AuthenticationManager в вашей конфигурации

Я последовал нескольким предложениям, упомянутым здесь, но у меня это не сработало. Следовательно, задавая вопрос здесь

  1. Как внедрить AuthenticationManager с помощью конфигурации Java в настраиваемом фильтре
  2. Spring требовался bean-компонент типа AuthenticationManager.

Может ли кто-нибудь объяснить мне, в чем проблема и как ее исправить?

Ошибка:

***************************
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);
    }
}

Ссылка на код, взятая из https://github.com/TechPrimers/spring-security-oauth-mysql-example, обновила только родительскую версию Spring Boot до 2.0.4.RELEASE, все начало ломаться.

27
0
52 756
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Похоже, это одно из «критических изменений», представленных Spring Boot 2.0. Я считаю, что ваш случай описан в Руководство по миграции Spring Boot 2.0.

В вашем классе WebSecurityConfigurerAdapter вам необходимо переопределить метод authenticationManagerBean и аннотировать его с помощью @Bean, то есть:

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

Более того, в вашем WebSecurityConfigurerAdapter вместо внедрения экземпляра AuthenticationManager с @Autowired вы можете просто использовать метод authenticationManagerBean(), то есть:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
{
    auth.parentAuthenticationManager(authenticationManagerBean());
        .userDetailsService(customUserDetailsService);
}
just add this to the AuthenticationManagerBuilder

@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;

Другие вопросы по теме