我正在使用 Spring Cloud 和 Netflix OSS Eureka 和 Ribbon 开发微服务。我有另一个作为 oauth-server 运行的服务,它提供 OAuth2 令牌。我所有的微服务都在 Eureka 注册,包括 oauth-server。如果我将 oauth-server 的硬编码 url 用作“clientCredentialsResourceDetails.setAccessTokenUri("http://localhost:9000/oauth/token");”,我的整个解决方案就可以工作。但是当我尝试使用 oauth-server 的 Eureka Discovered url 时,例如 "clientCredentialsResourceDetails.setAccessTokenUri("http://oauth-server/oauth/token");" 我收到错误: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;
}
我搜索了很多文档和在线帮助,但这些解决方案都不起作用。我认为这应该是一个简单的配置问题,现在已经耗尽了我两天的努力。