我正在使用OAuth2RestTemplate以便通过REST请求传递oauth令牌。但是,我现在需要对url进行硬编码,例如
restTemplate.postForLocation("http://localhost:5555/other-service2/message", "Message")
而当我使用自己创建的带注释的Ribbon(使用@LoadBalanced)RestTemplate bean时,我可以做类似
的操作 restTemplate.postForLocation("http://service1/other-service2/message", "Message")
这是因为,当您使用LoadBalanced时,它将自动使其成为Ribbon Rest Template,使您可以使用服务发现功能或Eureka,但是当您使用@Loadbalanced注释OAuth2RestTemplate bean时,它将在发生错误尝试使用OAuth2RestTemplate时显示运行时,
o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class java.lang.IllegalStateException, No instances available for localhost
我的OAuth2RestTemplate创建类似于
@LoadBalanced
@Bean
public OAuth2RestTemplate restTemplate(final UserInfoRestTemplateFactory factory) {
final OAuth2RestTemplate userInfoRestTemplate = factory.getUserInfoRestTemplate();
return userInfoRestTemplate;
}
如何在OAuth2RestTemplate上使用服务发现功能以及Eureka功能区的负载平衡功能?
答案 0 :(得分:3)
我认为这是您可以尝试的方法。
在我的项目中,我们还将OAuth2,Eureka,Ribbon用于微服务相互通信。为了将Ribbon与OAuth2结合使用,我们采取的方法有些不同。
首先,我们保持restTemplate不变。
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
但是,我们创建了FeignClientIntercepter来实现RequestIntercepter,当通过restTemplate发出请求时,该设置会为OAuth设置授权令牌。
@Component
public class UserFeignClientInterceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_TOKEN_TYPE = "Jwt";
@Override
public void apply(RequestTemplate template) {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null && authentication
.getDetails() instanceof OAuth2AuthenticationDetails) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication
.getDetails();
template.header(AUTHORIZATION_HEADER,
String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
}
}
}
如果您尝试创建spring msa项目,我宁愿使用 Feign-client ,而不是restTemplate。
@FeignClient("your-project-name")
public interface YourProjectClient {
@GetMapping("your-endpoint")
JsonObject getSomething();