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

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

  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, вещи начали ломаться.

1 Ответ

0 голосов
/ 09 сентября 2018

Похоже, это одно из "критических изменений", появившихся в 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...