feign.feignException$Unauthorized:[401] during [GET] to xxx…:

在SpringCloud的模块调用中,新增的模块实现其功能时调用其他模块的相关方法。在进行接口调用测试时,服务端会报出一个错误,Feign远程调用时没有权限;

在这里插入图片描述

问题分析

在调用方法的时候, 请求头中的 Authorization 是传递了的, 为什么Feign远程调用时, 报出没有权限这样的错误呢 ?

原因

Feign在进行远程调用时, 默认是没有将请求头继续往下传递的, 而系统微服务接入认证之后, 必须携带JWT令牌才可以访问, 没有携带令牌就访问系统服务, 就会出现401 , 未认证错误。

解决办法

使用Feign的拦截器来解决, 拦截所有的feign的远程调用, 在进行远程调用时, 拦截住请求, 并让请求头Authorization 继续往下传递。

@Component
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String authorization = request.getHeader("Authorization");
            template.header("Authorization", authorization);

        }
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐