问题描述
现在有两个服务,一个 user-service 服务作为服务提供者,另一个 resource-service 服务作为服务消费者,当消费者进行远程调用服务者提供的服务时出现未授权错误Unauthorized: [401]。
问题原因
在 Feign 在进行远程调用时, 默认是没有将请求头继续往下传递的, 而系统微服务接入认证之后, 必须携带 token 才可以访问, 没有携带令牌就访问系统服务, 就会出现401 Unauthorized 错误。
解决办法
创建 Feign 的拦截器, 拦截所有的 Feign 的远程调用。在进行远程调用时, 拦截住请求,并让请求头 Authorization 继续往下传递。
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//添加token
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
template.header(HttpHeaders.AUTHORIZATION, header);
}
}
参考文章:https://blog.csdn.net/weixin_44249188/article/details/118640140
推荐链接
发表评论