前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springcloud 微服务之间传递token解决方案

springcloud 微服务之间传递token解决方案

作者头像
用户2235302
发布2019-04-29 18:50:35
3.4K0
发布2019-04-29 18:50:35
举报

后续更新地址: https://www.aiprose.com/blog/36

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

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

代码语言:javascript
复制
hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE  #加上这个就可以获取到HttpServletRequest
          thread:
            timeoutInMilliseconds: 10000

2.服务A中加入 FeginInterceptor

代码语言:javascript
复制
@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.04.19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档