java - 已经使用 springSecurityFilterChain 构建了异常

标签 java spring spring-security

我正在尝试构建使用 Spring 安全性的应用程序,但出现异常:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built

我不知道是什么原因造成的。您可以在下面看到配置:

@Configuration
public class OAuth2SecurityConfiguration {

// This first section of the configuration just makes sure that Spring Security picks
// up the UserDetailsService that we create below. 
@Configuration
@EnableWebSecurity
protected static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    protected void registerAuthentication(
            final AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

/**
 *  This method is used to configure who is allowed to access which parts of our
 *  resource server (i.e. the "/video" endpoint) 
 */
@Configuration
@EnableResourceServer
protected static class ResourceServer extends
        ResourceServerConfigurerAdapter {

    private static final String VIDEO_ID = "video";

    // This method configures the OAuth scopes required by clients to access
    // all of the paths in the video service.
    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();

        http
        .authorizeRequests()
            .antMatchers("/oauth/token").anonymous();


        // If you were going to reuse this class in another
        // application, this is one of the key sections that you
        // would want to change

        // Require all GET requests to have client "read" scope
        http
        .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/**")
            .access("#oauth2.hasScope('read')");

        // Require all other requests to have "write" scope
        http
        .authorizeRequests()
            .antMatchers("/**")
            .access("#oauth2.hasScope('write')");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
         resources.resourceId(VIDEO_ID);
    }

}

/**
 * This class is used to configure how our authorization server (the "/oauth/token" endpoint) 
 * validates client credentials.
 */
@Configuration
@EnableAuthorizationServer
@Order(Ordered.LOWEST_PRECEDENCE - 100)
protected static class OAuth2Config extends
        AuthorizationServerConfigurerAdapter {

    // Delegate the processing of Authentication requests to the framework
    @Autowired
    private AuthenticationManager authenticationManager;

    // A data structure used to store both a ClientDetailsService and a UserDetailsService
    private ClientAndUserDetailsService combinedService_;

    /**
     * 
     * This constructor is used to setup the clients and users that will be able to login to the
     * system. This is a VERY insecure setup that is using hard-coded lists of clients / users /
     * passwords and should never be used for anything other than local testing
     * on a machine that is not accessible via the Internet. Even if you use
     * this code for testing, at the bare minimum, you should consider changing the
     * passwords listed below and updating the VideoSvcClientApiTest.
     * 
     * @param auth
     * @throws Exception
     */
    public OAuth2Config() throws Exception {

        // If you were going to reuse this class in another
        // application, this is one of the key sections that you
        // would want to change


        // Create a service that has the credentials for all our clients
        ClientDetailsService csvc = new InMemoryClientDetailsServiceBuilder()
                // Create a client that has "read" and "write" access to the
                // video service
                .withClient("mobile").authorizedGrantTypes("password")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read","write").resourceIds("video")
                .and()
                // Create a second client that only has "read" access to the
                // video service
                .withClient("mobileReader").authorizedGrantTypes("password")
                .authorities("ROLE_CLIENT")
                .scopes("read").resourceIds("video")
                .accessTokenValiditySeconds(3600).and().build();

        // Create a series of hard-coded users. 
        UserDetailsService svc = new InMemoryUserDetailsManager(
                Arrays.asList(
                        User.create("admin", "pass", "ADMIN", "USER"),
                        User.create("user0", "pass", "USER"),
                        User.create("user1", "pass", "USER"),
                        User.create("user2", "pass", "USER"),
                        User.create("user3", "pass", "USER"),
                        User.create("user4", "pass", "USER"),
                        User.create("user5", "pass", "USER")));

        // Since clients have to use BASIC authentication with the client's id/secret,
        // when sending a request for a password grant, we make each client a user
        // as well. When the BASIC authentication information is pulled from the
        // request, this combined UserDetailsService will authenticate that the
        // client is a valid "user". 
        combinedService_ = new ClientAndUserDetailsService(csvc, svc);
    }

    /**
     * Return the list of trusted client information to anyone who asks for it.
     */
    @Bean
    public ClientDetailsService clientDetailsService() throws Exception {
        return combinedService_;
    }

    /**
     * Return all of our user information to anyone in the framework who requests it.
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return combinedService_;
    }

    /**
     * This method tells our AuthorizationServerConfigurerAdapter to use the delegated AuthenticationManager
     * to process authentication requests.
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    /**
     * This method tells the AuthorizationServerConfigurerAdapter to use our self-defined client details service to
     * authenticate clients with.
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        clients.withClientDetails(clientDetailsService());
    }

}

}

最佳答案

注释或构建对象之一正在触发安全上下文构建两次。

尝试从 SecurityConfig 类中删除 @EnableWebSecurity 注释。 SpringBoot 可能会在幕后自动为您注入(inject)它。

如果这不起作用,请尝试注释掉 ClientDetailsS​​ervice 上的 .build() 调用(或整个对象)。如果该链中的某些内容创建了安全上下文,则可能会导致该问题。

关于java - 已经使用 springSecurityFilterChain 构建了异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59988231/

相关文章:

java - Spring security JDBC 身份验证是否会在每个请求时访问数据库

javascript - 在 JavaScript 中的 Thymeleaf 转义表达式中使用 Spring Security

angularjs - 如何配置 Spring Security 发送 'X-CSRF-TOKEN' ?

java - 自己的国际化支持就在眼前

java - setParameterList() 不返回完整结果集

java - Spring - 使用 Web 服务时未加载属性文件中的值

javascript - 语法错误: Unexpected token S, AngularJS,Spring

java - Eclipse 自动改变视角

java - 在 Java 11 中重构使用不同对象的资源的尝试

Spring Boot @EnableAutoConfiguration 根据属性有条件地排除类