微服务之间认证

微服务之间认证:

如上图:由于微服务直接调用也需要传递token 进行认证,而因为微服务之间并没有传递头文件,所以我们可以定义一个拦截器,每次微服务调用之前都先检查下头文件,将请求的头文件中的令牌数据存储到header 传递给被调用的微服务即可,微服务此时公钥自动校验头信息如果校验通过则放行请求,可以调用。

(1)创建拦截器

在changgou-service-order微服务中创建一个com.changgou.order.interceptor.MyFeignInterceptor拦截器,并将所有头文件数据再次加入到Feign请求的微服务头文件中,代码如下:

@Component
public class MyFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            //使用RequestContextHolder工具获取request相关变量
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                //取出request
                HttpServletRequest request = attributes.getRequest();
                //获取所有头文件信息的key
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        //头文件的key
                        String name = headerNames.nextElement();
                        //头文件的value
                        String values = request.getHeader(name);
                        //将令牌数据添加到头文件中
                        requestTemplate.header(name, values);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

(2)测试

我们发现这块的ServletRequestAttributes始终为空,RequestContextHolder.getRequestAttributes()该方法是从ThreadLocal变量里面取得相应信息的,当hystrix断路器的隔离策略为THREAD时,是无法取得ThreadLocal中的值。

解决方案:

  • hystrix隔离策略换为SEMAPHORE
  • 关闭hystirx

修改changgou-web-order的application.yml配置文件,在application.yml中添加如下代码,代码如下:

#hystrix 配置
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000
          strategy: SEMAPHORE

再次测试,效果如下:

发布了124 篇原创文章 · 获赞 76 · 访问量 5657

猜你喜欢

转载自blog.csdn.net/weixin_45151795/article/details/105247305