【发布时间】:2017-06-23 19:53:21
【问题描述】:
我正在设置一个独立的 OAuth2 资源服务器,它似乎没有对请求进行身份验证,使用没有承载令牌的 CURL 调用似乎无论如何都能成功。或者,我尝试设置全局方法安全性,所有请求都被错误拒绝
An authentication object could not be found in the current security context
即使在相关请求上设置了@PreAuthorize('submitAll()')。我很高兴采取任何一种方式来使身份验证正常工作(方法级别的安全性或检查令牌的正确配置)。
这里是代码。
@Configuration
@EnableResourceServer
@EnableWebSecurity
class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Bean
public ResourceServerTokenServices tokenService() {
RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setClientId("commsuite");
tokenServices.setClientSecret("secret");
tokenServices.setCheckTokenEndpointUrl("http://localhost:10386/oauth/check_token");
return tokenServices;
}
@Bean
public AuthenticationManager authenticationManager() {
final OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
oAuth2AuthenticationManager.setTokenServices(tokenService());
return oAuth2AuthenticationManager;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenService()).authenticationManager(authenticationManager());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/2/**").authorizeRequests().anyRequest().authenticated();
}
}
/* Here is the api controller code with the call */
@RequestMapping(value="/test", method = RequestMethod.GET, produces = {"text/plain"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody
String testEndpoint() {
return "Gnarly Dudes\n";
}
在这种情况下,没有承载令牌的原始 curl 调用会成功。
作为第二种情况,我尝试使用方法级别安全注释,方法是添加以下代码,然后将@PreAuthorize("permitAll()") 添加到上面的testEndpoint 方法中。在这种情况下,我在原始 CURL 调用和使用从单独的身份验证服务器获得的有效不记名令牌的调用中都收到 Authentication object could not be found 错误。我怀疑我错过了一些东西。谢谢...
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
【问题讨论】:
标签: authentication spring-security spring-security-oauth2 oauth2 spring-oauth2