RestTemplate 拦截器线程安全?

问题描述

this tutorial 中,作者为 RestTemplate 中的 @Controller 使用了一个全局变量。 对于传入的请求,他从请求中提取 Bearer 令牌,并添加一个拦截器,将令牌添加RestTemplate 的传出请求中。

我认为,可能存在竞争条件。第二个用户的请求可能会从第一个用户那里获得拦截器,因此作为第一个用户进行身份验证。

据 Okta 称,他们测试了代码并且没有遇到任何竞争条件。 Spring 中是否有某种机制可以确保这一点?

解决方法

RestTemplate 本身 is thread safe

有问题的代码:

restTemplate.getInterceptors().add(getBearerTokenInterceptor(accessToken.getTokenValue()));

... 看起来确实有问题。我不确定,因为我没有尝试查看它是用于单元测试还是集成测试。

来自the getInterceptors() Javadoc

/**
 * Get the request interceptors that this accessor uses.
 * <p>The returned {@link List} is active and may be modified. Note,* however,that the interceptors will not be resorted according to their
 * {@linkplain AnnotationAwareOrderComparator#sort(List) order} before the
 * {@link ClientHttpRequestFactory} is built.
 */

您可以尝试改用 setInterceptors(),因为它取代了拦截器。