我们希望设置一个提供RESTAPI的微服务,以便将其配置为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我创建了一个模拟请求拦截器,该拦截器从模拟请求标头中的自动安装的OAuth2Rest操作模板设置访问令牌
@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应用程序创建AuthorizationCodeResource详细信息的实例,但不创建仅用于非Web应用程序的所需ClientCretionalsResource详细信息。最后,no access token privider负责资源详细信息,调用失败
AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:146)
我试图覆盖自动配置,但失败了。有人能给我一个提示吗?
要关闭这段自动配置,您可以设置Spring. oaut2.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;
}
}