1. /**
    2. * Feign统一Token拦截器
    3. */
    4. @Component
    5. public class FeignTokenInterceptor implements RequestInterceptor {
    6. @Override
    7. public void apply(RequestTemplate requestTemplate) {
    8. if(null==getHttpServletRequest()){
    9. //此处省略日志记录
    10. return;
    11. }
    12. //将获取Token对应的值往下面传
    13. requestTemplate.header("oauthToken", getHeaders(getHttpServletRequest()).get("oauthToken"));
    14. }
    15. private HttpServletRequest getHttpServletRequest() {
    16. try {
    17. return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    18. } catch (Exception e) {
    19. return null;
    20. }
    21. }
    22. /**
    23. * Feign拦截器拦截请求获取Token对应的值
    24. * @param request
    25. * @return
    26. */
    27. private Map<String, String> getHeaders(HttpServletRequest request) {
    28. Map<String, String> map = new LinkedHashMap<>();
    29. Enumeration<String> enumeration = request.getHeaderNames();
    30. while (enumeration.hasMoreElements()) {
    31. String key = enumeration.nextElement();
    32. String value = request.getHeader(key);
    33. map.put(key, value);
    34. }
    35. return map;
    36. }
    37. }

    代码见:
    https://github1s.com/springcloud/spring-cloud-code/blob/HEAD/ch4-5/ch4-5-consumer/src/main/java/cn/springcloud/book/feign/Interceptor/FeignTokenInterceptor.java#L14-L53