JWT如何在Spring Cloud微服务系统中在服务相互调时传递

转载请标明出处:
http://blog.csdn.net/forezp/article/details/78676036
本文出自方志朋的博客

个人博客纯净版:https://www.fangzhipeng.com/architecture/2018/01/01/springcloud-jwt.html

在微服务系统中,为了保证微服务系统的安全,常常使用jwt来鉴权,但是服务内部的相互调用呢。经常有人在微信上问我,我给出一个解决办法,采用Feign的拦截器。

在Feign中开启了hystrix,hystrix默认采用的是线程池作为隔离策略。线程隔离有一个难点需要处理,即隔离的线程无法获取当前请求线程的Jwt,这用ThredLocal类可以去解决,但是比较麻烦,所以我才用的是信号量模式。
在application.yml配置文件中使用一下配置:

hystrix.command.default.execution.isolation.strategy: SEMAPHORE

写一个Feign的拦截器,Feign在发送网络请求之前会执行以下的拦截器,代码如下:


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by fangzhipeng on 2017/7/28.
 */
@Component
public class JwtFeignInterceptor implements RequestInterceptor {

    private final String key = "Authorization";


    @Override
    public void apply(RequestTemplate template) {

        if (!template.headers().containsKey(key)) {
            String currentToken = UserUtils.getCurrentToken();
            if (!StrUtil.isEmpty(currentToken)){
                template.header(key, currentToken);
            }
        }
    }
}

也可以参考这篇文章:http://www.spring4all.com/article/948

更多阅读

史上最简单的 SpringCloud 教程汇总

SpringBoot教程汇总

Java面试题系列汇总


扫码关注公众号有惊喜

(转载本站文章请注明作者和出处 方志朋的博客

  • 1
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值