【发布时间】:2016-07-14 00:49:09
【问题描述】:
我正在使用 Spring Security OAuth2 和一个运行良好的非常基本的配置。我现在想要一个单独的WebSecurityConfigurerAdapter,其中包含确定某人是否有权访问某些端点的自定义逻辑。但是,无论我尝试什么,它都不会执行。以下是我的OAuth2 配置和我对该主题的发现。授权服务器:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private AuthenticationManagerBuilder authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)throws Exception {
endpoints.authenticationManager(authentication -> authenticationManager.getOrBuild().authenticate(authentication)).tokenStore(tokenStore);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("CLIENT_NAME")...;
}
}
资源服务器:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
@Override
public void configure(final ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
}
}
到目前为止一切顺利。但是,当自定义 WebSecurityConfigurerAdapter 开始起作用时,我开始遇到问题。由于EnableResourceServer-annotated bean 创建了一个带有Order(3) 的WebSecurityConfigurerAdapter,它首先在每个请求上执行,用户已成功验证/授权,但我的WebSecurityConfiguration 中的自定义逻辑未执行。另一方面,如果我将WebSecurityConfiguration 设置为Order(2) 或更少,则会执行自定义access 规则,但它总是说它们来自匿名用户(因为@ 创建的bean 中的规则987654334@ 未执行)。
@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/...");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers(HttpMethod.GET, "/path/**")
.access("@security.hasPermission(authentication, 'SOME', 'VALUE')");
http.authorizeRequests().anyRequest().authenticated();
}
}
顺便说一句,access 规则中的 @security 引用只是一个简单的命名 Spring bean:
@Component("security")
public class SecurityService {
public boolean hasPermission(Authentication authentication, String param, String anotherParam) { ... }
}
我有集成测试来验证WebSecurityConfiguration 中的自定义访问规则并且它们有效(因为我跳过了那里的身份验证)。我希望能够将资源服务器仅用于身份验证,然后将我的自定义 http 安全性用于授权。
【问题讨论】:
标签: spring spring-security spring-boot spring-security-oauth2