我正在使用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
。是否有任何配置可以修改此行为?
答案 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);