RestTemplate OAuth2请求访问令牌通过GET请求而不是POST

时间:2017-09-07 07:30:52

标签: spring spring-security-oauth2 resttemplate

我正在使用Spring RestTemplate向受OAuth2保护的资源服务器发出请求。下面是初始化RESTTemplate的代码。

ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setUsername(userName);
resourceDetails.setPassword(password);
resourceDetails.setAccessTokenUri(root + accessTokenURI);
resourceDetails.setClientId(clientId);
resourceDetails.setClientSecret(clientSecret);
resourceDetails.setGrantType(grantType);
resourceDetails.setScope(Arrays.asList(scope));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

RestTemplate rest = new OAuth2RestTemplate(resourceDetails, clientContext);

Spring RestTemplate默认使用POST请求从授权服务器获取access_token。我有一个独特的要求。我希望RestTemplate使用GET来获取access_token而不是POST。是否有任何配置可以修改此行为?

1 个答案:

答案 0 :(得分:3)

在查看spring-security-oauth项目的内部结构后,我找到了解决方案。它需要覆盖ResourceOwnerPasswordAccessTokenProvider类,并在AccessTokenProvider类中将其设置为OAuth2RestTemplate。这是怎么回事。

package com.acme;

import org.springframework.http.HttpMethod;

public class ResourceOwnerPasswordAccessTokenProvider extends org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider {

  @Override
  protected HttpMethod getHttpMethod() {
    return HttpMethod.GET;
  }
}

并初始化OAuth2RestTemplate

ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setUsername(userName);
resourceDetails.setPassword(password);
resourceDetails.setAccessTokenUri(root + accessTokenURI);
resourceDetails.setClientId(clientId);
resourceDetails.setClientSecret(clientSecret);
resourceDetails.setGrantType(grantType);
resourceDetails.setScope(Arrays.asList(scope));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

OAuth2RestTemplate rest = new OAuth2RestTemplate(resourceDetails, clientContext);

// Set the overridden ResourceOwnerPasswordAccessTokenProvider class instance to OAuth2RestTemplate
AccessTokenProvider accessTokenProvider = new com.acme.ResourceOwnerPasswordAccessTokenProvider();
rest.setAccessTokenProvider(accessTokenProvider);