【发布时间】:2017-12-11 05:09:36
【问题描述】:
我正在尝试使用 Spring Secruity 的 OAuth API 从外部发布的 API 获取访问令牌。
这个 curl 命令有效(它的内容就是我获取访问令牌所需的全部内容):
curl -X POST \
https://api.app.com/v1/oauth/token \
-H 'content-type: application/x-www-form-urlencoded' \
-d'grant_type=client_credentials&client_id=bcfrtew123&client_secret=Y67493012'
运行此 curl 命令后,我能够从外部服务获取访问令牌。
使用 Spring Security OAuth API 时:
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
像这样设置我的 SpringMVC 控制器的方法:
@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded")
public OAuth2AccessToken getAccessToken(@RequestParam(value="client_id", required=true) String clientId, @RequestParam(value="client_secret", required=true) String clientSecret) throws Exception {
String tokenUri = "https://api.app.com/v1/oauth/token";
ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setAccessTokenUri(tokenUri);
resourceDetails.setClientId(clientId);
resourceDetails.setClientSecret(clientSecret);
resourceDetails.setGrantType("client_credentials");
resourceDetails.setScope(Arrays.asList("read", "write"));
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
OAuth2AccessToken token = oauth2RestTemplate.getAccessToken();
return token;
}
当我从本地 tomcat 实例调用 getAccessToken 时:
access_denied
error_description=Unable to obtain a new access token for resource 'null'.
The provider manager is not configured to support it.
问题:
- 我在这里缺少什么?这需要一些注释吗?是否存在未设置或需要的属性?
(请注意,内容类型需要是“application/x-www-form-urlencoded”...)
如何使用 Spring Security OAuth API 模拟有效的 curl 命令?
会不会是我在 RequestParameters 中设置的默认值?
如果成功,我该如何设置,以便在发出任何请求之前始终预加载访问令牌?
【问题讨论】:
标签: java spring-mvc curl oauth spring-security-oauth2