美文网首页
2019-12-04 Spring Cloud 微服务之间传递t

2019-12-04 Spring Cloud 微服务之间传递t

作者: 请让我想一想 | 来源:发表于2019-12-04 11:31 被阅读0次

    在springcloud 微服务中大部分是通过token来验证用户的

    那么有个问题,假设现在有A服务,B服务,外部使用RESTApi请求调用A服务,在请求头上有token字段,A服务使用完后,B服务也要使用,如何才能把token也转发到B服务呢,最差的解决办法就是吧token放到请求参数中,但是这样第一个是明文传输,第二个是比较麻烦,前端每次都要加个参数。这里可以使用Feign的RequestInterceptor,把request里的请求参数包括请求头全部复制到feign的request里,但是直接使用一般情况下HttpServletRequest上下文对象是为空的,其实加个配置就可以解决。

    1.服务A中 application.yml 加入如下配置

    hystrix:
      command:
        default:
          execution:
            isolation:
              strategy: SEMAPHORE  #加上这个就可以获取到HttpServletRequest
              thread:
                timeoutInMilliseconds: 10000
    

    2.服务A中加入 FeginInterceptor

    @Configuration
    public class FeginInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate requestTemplate) {
           try {
               Map<String,String> headers = getHeaders();
               for(String headerName : headers.keySet()){
                   requestTemplate.header(headerName, headers.get(headerName));
               }
           }catch (Exception e){
               e.printStackTrace();
           }
        }
        private Map<String, String> getHeaders(){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            Map<String, String> map = new LinkedHashMap<>();
            Enumeration<String> enumeration = request.getHeaderNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
            return map;
        }
    
    }
    

    若服务B或C也想传递token,加上上述A配置即可

    相关文章

      网友评论

          本文标题:2019-12-04 Spring Cloud 微服务之间传递t

          本文链接:https://www.haomeiwen.com/subject/stgkgctx.html