java - 已经使用 springSecurityFilterChain 构建了异常
问题描述
我正在尝试构建和使用 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 可能会在幕后自动为您注入。
如果这不起作用,请尝试.build()
在ClientDetailsService
. 如果该链中的某些内容创建了安全上下文,则可能会导致该问题。
推荐阅读
- apache - Hadoop 全序分区
- java - 针对 XSD 验证多个 XML 文件的最佳方法是什么?
- sql-server - 表未显示在 SQL Server Management Studio 和 Visual Studio 中
- android - 为什么这不能作为 Kotlin 中的返回类型?
- hazelcast - 当具有特定值的条目在 Hazelcast 上可用时如何获得通知?
- django - TypeError:上下文必须是字典而不是 HttpResponseRedirect
- for-loop - 双模运算符
- pouchdb - PouchDB 如何响应 Couch DB 验证错误?
- python - tensorflow lite:将重新训练的图形模型转换为 lite 格式时出错
- javascript - 如何通过 Angular 4 中的 App 组件访问私有属性?