问题
I am working on microservices with Spring Cloud and Netflix OSS Eureka and Ribbon. I have another service running as oauth-server which provides OAuth2 token. All my microservices are registered with Eureka including oauth-server. My whole solution works if I use hardcoded url of oauth-server as "clientCredentialsResourceDetails.setAccessTokenUri("http://localhost:9000/oauth/token");" but when I try to use Eureka Discovered url of oauth-server like "clientCredentialsResourceDetails.setAccessTokenUri("http://oauth-server/oauth/token");" I get error: java.net.UnknownHostException: oauth-server
MyConfig.java
@Bean(name = "myOauth2RestTemplate")
@LoadBalanced
public OAuth2RestOperations restTemplate(RestTemplateCustomizer customizer,
ClientCredentialsResourceDetails resourceDetails) {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
ClientCredentialsAccessTokenProvider provider = new ClientCredentialsAccessTokenProvider();
restTemplate.setAccessTokenProvider(provider);
customizer.customize(restTemplate);
return restTemplate;
}
@Bean
public ClientCredentialsResourceDetails resourceDetails() {
ClientCredentialsResourceDetails clientCredentialsResourceDetails = new ClientCredentialsResourceDetails();
clientCredentialsResourceDetails.setAccessTokenUri("http://oauth-server/oauth/token");
clientCredentialsResourceDetails.setId("1");
clientCredentialsResourceDetails.setClientId("candy");
clientCredentialsResourceDetails.setClientSecret("123");
clientCredentialsResourceDetails.setScope(Arrays.asList("read", "write"));
clientCredentialsResourceDetails.setGrantType("client_credentials");
return clientCredentialsResourceDetails;
}
MyController.java
@Autowired
@Qualifier("myOauth2RestTemplate")
@LoadBalanced
private OAuth2RestTemplate myOauth2RestTemplate;
@GetMapping("/secure/hello")
public String getSecureData() {
String result = myOauth2RestTemplate.getForObject("http://securems/secure/hello", String.class);
return result;
}
I have searched through a lot of documentation and online help, but those solutions didn't work. I thought this should have been an easy configuration issue has now eaten up my two days of effort.
回答1:
I was finally able to make it work with following code:
@Bean
@LoadBalanced
public OAuth2RestTemplate restTemplate(SpringClientFactory clientFactory) {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails());
RibbonLoadBalancerClient ribbonLoadBalancerClient = new RibbonLoadBalancerClient(clientFactory);
LoadBalancerInterceptor loadBalancerInterceptor = new LoadBalancerInterceptor(ribbonLoadBalancerClient);
ClientCredentialsAccessTokenProvider accessTokenProvider = new ClientCredentialsAccessTokenProvider();
accessTokenProvider.setInterceptors(Arrays.asList(loadBalancerInterceptor));
restTemplate.setAccessTokenProvider(accessTokenProvider);
return restTemplate;
}
来源:https://stackoverflow.com/questions/62574591/oauth2resttemplate-with-ribbon-eureka