Spring和OAuth2处于非交互模式,具有client_credentials授权类型

时间:2016-11-14 22:02:09

标签: java spring spring-security-oauth2 oauth2

我有一个使用OAuth2身份验证的REST服务,它提供了一个端点来请求具有client_credentials授权类型的令牌。该应用程序基于Spring Boot。

到目前为止,我发现我可以通过以下方式请求令牌:

@SpringBootApplication
@EnableOAuth2Client
public class App extends WebSecurityConfigurerAdapter {

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

    //...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Does nothing - to allow unrestricted access
    }    

    @Bean
    protected OAuth2RestTemplate myTemplate() {
        ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
        details.setAccessTokenUri("http://localhost:8080/oauth/token");
        details.setClientId("theClient");
        details.setClientSecret("thePassword");
        return new OAuth2RestTemplate(details, oauth2ClientContext);
    }

}

@RestController
public class TestController {

    @Autowired
    OAuth2RestTemplate myTemplate;

    @RequestMapping("/token")
    private String getToken() {
        return myTemplate.getAccessToken().getValue();
    }

}

几乎有效,但每当我调用/token端点时,都有例外:

org.springframework.security.authentication.InsufficientAuthenticationException: Authentication is required to obtain an access token (anonymous not allowed)
    at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:88) ~[spring-security-oauth2-2.0.9.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221) ~[spring-security-oauth2-2.0.9.RELEASE.jar:na]
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173) ~[spring-security-oauth2-2.0.9.RELEASE.jar:na]
    ...

异常抛出here,但我不确定如何让Spring使用除AnonymousAuthenticationToken之外的上下文身份验证。事实上,我不希望客户端进行任何身份验证,因为匿名是完全可以的。我怎样才能做到这一点?

0 个答案:

没有答案