spring cloud Feign远程调用服务,添加验证信息解决拦截器拦截问题

使用spring cloud 做微服务时,例如:做A服务时需要通过Feign调用B服务。但是我们的B服务做了某些权限验证。需要验证header或者token什么的。如果某没有token,会被阻止调用。那如何添加token呢。如果每个方法都手动设置headers,那未免太麻烦。可以通过Feign配置,自动帮我们添加请求header。

@Configuration
public class FeignConfig implements RequestInterceptor {


  @Value("${superToken:xxxxxxxxxxxxxxxxxxxx}")
  private String superToken;

  @Bean
  Request.Options feignOptions() {
    return new Request.Options(30000, 60000);
  }

  @Bean
  public Decoder feignDecoder() {
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(
        fastConverter);
    return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
  }

  @Override
  public void apply(RequestTemplate requestTemplate) {
    Map<String, String> headers = getHeaders(getHttpServletRequest());
    if (null == headers || !headers.keySet().contains("authorization") || StringUtils
        .isEmpty(headers.get("authorization"))) {
      requestTemplate.header(XRequestIDFilter.X_REQUEST_ID, UUID.randomUUID().toString());
      requestTemplate.header("across_auth", "true");
      requestTemplate.header("Authorization", "Bearer " + superToken);
    } else {
      requestTemplate.header("Authorization", headers.get("authorization"));
      requestTemplate.header(XRequestIDFilter.X_REQUEST_ID, headers.get("x-request-id"));
    }

  }

  private HttpServletRequest getHttpServletRequest() {
    try {
      return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    } catch (Exception e) {
      return null;
    }
  }

  private Map<String, String> getHeaders(HttpServletRequest request) {
    if (null == request) {
      return null;
    }
    Map<String, String> map = new LinkedHashMap<>();
    Enumeration<String> enumeration = request.getHeaderNames();
    while (enumeration.hasMoreElements()) {
      String key = enumeration.nextElement().toLowerCase();
      String value = request.getHeader(key);
      map.put(key, value);
    }
    return map;
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值