spring cloud微服务增加oauth2权限后 feign调用报null错误
在授权服务里,用户通过用户名密码,或者手机和验证码等方式登陆之后,在http头里会有授权的标识,在客户端调用时,需要添加当时有效的token才可以正常访问被授权的页面。
Content-Type:application/json
Authorization:Bearer d79c064c-8675-4047-a119-fac692e447e8
而在业务层里,服务与服务之间使用feign来实现调用,而授权的代码我们可以通过拦截器实现,在feign请求之前,把当前服务的token添加到目标服务的请求头就可以了,一般是这样实现的。
/**
* 发送FeignClient设置Header信息.
* http://www.itmuch.com/spring-cloud-sum/hystrix-threadlocal/
* Hystrix传播ThreadLocal对象
*/
@Component
public class TokenFeignClientInterceptor implements RequestInterceptor {
/**
* token放在请求头.
*
* @param requestTemplate 请求参数
*/
@Override
public void apply(RequestTemplate requestTemplate) {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
requestTemplate.header("Authorization", request.getHeader("Authorization"));
}
}
}
上面的拦截器代码没有什么问题,也很好理解,但事实上,当你的feign开启了hystrix功能,如果开启了,需要把hystrix的策略进行修改,默认是THREAD的,这个级别时ThreadLocal是空的,所以你的授权不能传给feign的拦截器.
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE