代码之家  ›  专栏  ›  技术社区  ›  katiex7

如何在OAuth2RestTemplate中使用Eureka名称

  •  1
  • katiex7  · 技术社区  · 7 年前

    我使用OAuth2RestTemplate来传递带有REST请求的oauth令牌。但是,我现在需要硬编码我的url,比如

    restTemplate.postForLocation("http://localhost:5555/other-service2/message", "Message")
    

     restTemplate.postForLocation("http://service1/other-service2/message", "Message")
    

    这是因为当您使用LoadBalanced时,它会自动使其成为一个功能区Rest模板,允许您使用服务发现特性或Eureka,但是当您使用@LoadBalanced注释oauth2restemplate bean时,它会在运行时抛出某种错误,当您尝试使用oauth2restemplate时,它会说

      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;
    }
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ted Kim    7 年前

    我想你可以试试。

    在我的项目中,我们还使用OAuth2、Eureka和Ribbon来实现微服务之间的通信。为了在OAuth2中使用Ribbon,我们采用的方法有些不同。

    首先我们保持rest模板不变。

      @LoadBalanced
      @Bean
      public RestTemplate restTemplate() {
    

    但是,我们创建了实现RequestIntercepter的FeignClientIntercepter,它在通过restemplate发出请求时为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()));
          }
        }
      }
    

    外国客户 而不是REST模板。

    @FeignClient("your-project-name")
    public interface YourProjectClient {
    
      @GetMapping("your-endpoint")
      JsonObject getSomething();
    
    推荐文章