【问题标题】:How to propagate token using Spring Feign Client如何使用 Spring Feign Client 传播令牌
【发布时间】:2023-02-20 04:40:46
【问题描述】:

我正在使用 Feign Client 调用另一个微服务,如下所示:

@FeignClient("employee")
public interface EmployeeFeignClient {

    @RequestMapping(
        method= RequestMethod.GET,
        value="/employee/code/{code}",
        consumes="application/json"
    )
    EmployeeResponseEntity getEmployeeByCode(@PathVariable("code") String code);
}

调用员工服务的服务将在其请求标头中包含身份验证承载令牌。我需要将相同的令牌传递给正在进行的服务调用。 试图找到如何实现相同但无法实现的方法。一些帮助会很好。

【问题讨论】:

标签: java spring spring-boot spring-cloud-feign


【解决方案1】:

之前有人回答过。

解决方案是使用@RequestHeader注解,而不是feign特定的注解

@FeignClient(name="Simple-Gateway")
interface GatewayClient {    
    @RequestMapping(method = RequestMethod.GET, value = "/gateway/test")
    String getSessionId(@RequestHeader("X-Auth-Token") String token);
}

【讨论】:

    【解决方案2】:

    像这样创建标头并传递给您的假装客户

    private HttpHeaders getHeaders(final HttpServletRequest httpServletRequest) {
            final HttpHeaders headers = new HttpHeaders();
            headers.add("authorization", httpServletRequest.getHeader("authorization"));
            return headers;
    

    Example 1

    或者很简单的添加拦截器

    @Component
    public class AuthFeignInterceptor implements RequestInterceptor {
    
        @Override
        public void apply(RequestTemplate template) {
            final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                final HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
                template.header(HttpHeaders.AUTHORIZATION, httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION));
            }
        }
    }
    

    Example 2

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2018-02-01
      • 2015-10-12
      • 2021-12-17
      • 2021-12-13
      • 2017-12-14
      • 2019-08-16
      • 2015-11-12
      • 2017-09-22
      相关资源
      最近更新 更多