OAuth2资源服务器未对请求进行身份验证

时间:2017-02-06 18:53:24

标签: authentication spring-security spring-security-oauth2 oauth2 spring-oauth2

我正在设置一个独立的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";
}

在这种情况下,没有承载令牌的原始卷曲调用成功。

作为第二种情况,我尝试使用方法级安全注释,添加以下代码,然后将@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();
    }
}

1 个答案:

答案 0 :(得分:0)

添加

后,您的代码适用于我

`public class AppSecurityInitializer扩展了AbstractSecurityWebApplicationInitializer {

}`

空类只是扩展以启用弹簧安全性