Spring 没有定义 AuthenticationManagerBuilder 类型的 bean

问题描述 投票:0回答:2

最近在我的 Spring REST API 中我遇到了一个奇怪的异常。 Spring 告诉我它没有找到任何

org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder

类型的 bean

它并不是每次都会出现,第一个修复方法是重新启动 IntelliJ IDEA 几分钟,然后一切都会正常工作。

但是现在,它不会部署在我的远程 tomcat 服务器上,因此我不知道如何处理它。

错误信息:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method authenticationManager in eu.side.thot.Application required a bean of type 'org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder' in your configuration.


Process finished with exit code 1

这是我的配置

应用程序.java

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }


    @Autowired
    private CustomUserDetailsService userDetailsService;

    /**
    * Set AuthenticationManager his UserDetailsService and PasswordEncoder so he can authenticate an user with a given username/password
    * */
    @Autowired
    public void authenticationManager(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(userDetailsService).passwordEncoder(new MD5PasswordEncoder());
    }
}

和 AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    private Logger log = Logger.getLogger(AuthorizationServerConfig.class);


    private static final int FIVE_HOURS_IN_S = 5*3600;
    private static final int MONTH_IN_S = 31*24*3600;

    private final AuthenticationManager authenticationManager;

    @Autowired
    public AuthorizationServerConfig(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer serverSecurityConfigurer){
        serverSecurityConfigurer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
        clients.inMemory().withClient("{client}")
                .authorizedGrantTypes("client-credentials", "password", "refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT")
                .scopes("read", "write", "trust")
                .resourceIds("oauth2resource")
                .accessTokenValiditySeconds(FIVE_HOURS_IN_S)
                .secret("{secret}").refreshTokenValiditySeconds(MONTH_IN_S);
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints){
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .exceptionTranslator(loggingExceptionTranslator());
    }

    @Bean
    public WebResponseExceptionTranslator loggingExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {
            @Override
            public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
                // This is the line that prints the stack trace to the log. You can customise this to format the trace etc if you like
                e.printStackTrace();

                // Carry on handling the exception
                ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
                HttpHeaders headers = new HttpHeaders();
                headers.setAll(responseEntity.getHeaders().toSingleValueMap());
                OAuth2Exception excBody = responseEntity.getBody();
                return new ResponseEntity<>(excBody, headers, responseEntity.getStatusCode());
            }
        };
    }

}

感谢您的帮助

更新:我的 API 有效,我没有改变任何东西...如果有人知道问题出在哪里,我很想听听它以便更好地理解 spring :)

java spring spring-security spring-bean
2个回答
0
投票

看来你错过了

compile group: 'org.springframework.security', name: 'spring-security-config', version: '5.0.3.RELEASE'

此外,用户应利用使用

@EnableWebSecurity
@EnableGlobalMethodSecurity

时可用的 Global AuthenticationManagerBuilder

0
投票

在类上使用 @EnableWebSecurity 进行注释允许我进行与安全相关的导入

© www.soinside.com 2019 - 2024. All rights reserved.