我们按以下步骤分析原因:
- 第一点,返回403说明调用接口时未经授权
- 第二点,若后端主线程中发现Request Header已经带着从前端发送的Authentication和接口参数,并且在子线程调用其他服务接口日志中打印获取RequestContextHolder.currentRequestAttributes为null
以上问题说明在调用接口服务时请求头信息丢失(Authentication),导致授权失败,调接口失败
我们去看下RequestContextHolder这个类的源代码,会发现问题
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<>("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
new NamedInheritableThreadLocal<>("Request context");
public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) {
if (attributes == null) {
resetRequestAttributes();
}
else {
if (inheritable) {
inheritableRequestAttributesHolder.set(attributes);
requestAttributesHolder.remove();
}
else {
requestAttributesHolder.set(attributes);
inheritableRequestAttributesHolder.remove();
}
}
源码解析
- List itemrequestAttributesHolder 是NamedThreadLocal对象,NamedThreadLocal继承ThreadLocal,用于存储数据,可保证线程之间数据的隔离,只允许当前线程获取到存入的值,所以不难理解,这就是子线程未获取到请求头信息的原因。
- 再注意inheritableRequestAttributesHolder 这个变量和setRequestAttributes方法,inheritableRequestAttributesHolder 对象类型是NamedInheritableThreadLocal ,继承InheritableThreadLocal,InheritableThreadLocal是用于线程之间数据共享的,而setRequestAttributes这个方法参数RequestAttributes 就是请求头信息,inheritable是boolean ,意思是是否共享,再看方法里的代码逻辑,如果要保证RequestAttributes 共享,则inheritable设置为true
- 因此,在主线程中我们只需要加上下面这行代码,问题迎刃而解。
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(),true);
或者
RequestContextHolder.setRequestAttributes(RequestContextHolder.currentRequestAttributes(),true);
到这里,这个问题就解决完毕,如果你也遇到过这样的问题,快拿去试试吧!