目标是使用 RequestInterceptor 从安全上下文中附加一些数据,但问题是调用SecurityContextHolder.getContext().getAuthentication()
总是返回 null,即使它不为 null(我确信 100%)。
据我了解,这是因为拦截器已创建并正在其他线程中运行。
我该如何解决这个问题并从安全上下文中获取实际数据?
我的服务:
@FeignClient(value = "api", configuration = { FeignConfig.class })
public interface DocumentService {
@RequestMapping(value = "/list", method = RequestMethod.GET)
DocumentListOperation list();
}
我的 FeignConfig 类:
@Bean
public RequestInterceptor requestInterceptor() {
return new HeaderInterceptor(userService);
}
public class HeaderInterceptor implements RequestInterceptor {
private UserService userService;
public HeaderInterceptor(UserService userService) {
this.userService = userService;
}
@Override
public void apply(RequestTemplate requestTemplate) {
Authentication a = SecurityContextHolder.getContext().getAuthentication()
requestTemplate.header("authentication", a.toString());
}
}