我们想要设置一个提供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,我创建了一个伪装请求拦截器,它从伪装请求 header 中的自动连接的OAuth2RestOperations模板设置了访问 token
@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。最后,无访问 token 特权者负责资源详细信息,并且调用失败
AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:146)
我试图覆盖自动配置,但失败了。有人可以给我一个提示怎么做吗?
最佳答案
要关闭此自动配置功能,可以设置spring.oauth2.client.clientId=
(空)(根据源代码),否则,您必须在@EnableAutoConfiguration
中“排除”它。如果这样做,您可以设置自己的OAuth2RestTemplate
并从您自己的配置中填写“真实”客户端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;
}
}
关于spring - 如何覆盖Spring Cloud OAuth2客户端自动配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29696671/