我们希望设置一个提供REST API的微服务,以便将其配置为OAuth2资源服务器。此服务还应充当具有客户端凭据授权的OAuth2客户端。这是配置:
spring.oauth2.client.id=clientCredentialsResource
spring.oauth2.client.accessTokenUri=http://localhost:9003/oauth/token
spring.oauth2.client.userAuthorizationUri=http://localhost:9003/oauth/authorize
spring.oauth2.client.grantType=client_credentials
spring.oauth2.client.clientId=<service-id>
spring.oauth2.client.clientSecret=<service-pw>
资源服务器部分正常工作。对于客户端部分,我们要使用Feign,Ribbon和Eureka:
@FeignClient("user")
public interface UserClient
{
@RequestMapping( method = RequestMethod.GET, value = "/user/{uid}")
Map<String, String> getUser(@PathVariable("uid") String uid);
}
基于问题的要点https://github.com/spring-cloud/spring-cloud-security/issues/56,我创建了一个假装请求拦截器,用于在假装请求标头中设置自动装配的OAuth2RestOperations模板中的访问令牌
@Autowired
private OAuth2RestOperations restTemplate;
template.header(headerName, String.format("%s %s", tokenTypeName, restTemplate.getAccessToken().toString()));
但是这给我带来了调用用户服务的错误:
error="access_denied", error_description="Unable to obtain a new access token for resource 'clientCredentialsResource'. The provider manager is not configured to support it.
正如我所看到的,OAuth2ClientAutoConfiguration始终为Web应用程序创建AuthorizationCodeResourceDetails实例,但不创建仅用于非Web应用程序的必需ClientCredentialsResourceDetails。最后,no access token privider负责资源细节,并且调用失败
AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:146)
我试图覆盖自动配置但失败了。有人可以给我一个提示怎么做?
答案 0 :(得分:8)
要关闭此自动配置,您可以设置spring.oauth2.client.clientId=
(空),(根据源代码),否则您必须排除&#34;排除&#34;它在@EnableAutoConfiguration
。如果你这样做,你可以设置自己的OAuth2RestTemplate
并填写&#34;真实&#34;来自您自己配置的客户端ID,例如
@Configuration
@EnableOAuth2Client
public class MyConfiguration {
@Value("myClientId")
String myClientId;
@Bean
@ConfigurationProperties("spring.oauth2.client")
@Primary
public ClientCredentialsResourceDetails oauth2RemoteResource() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
details.setClientId(myClientId);
return details;
}
@Bean
public OAuth2ClientContext oauth2ClientContext() {
return new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest());
}
@Bean
@Primary
public OAuth2RestTemplate oauth2RestTemplate(
OAuth2ClientContext oauth2ClientContext,
OAuth2ProtectedResourceDetails details) {
OAuth2RestTemplate template = new OAuth2RestTemplate(details,
oauth2ClientContext);
return template;
}
}