public class RequestContext {
public static final String REQUEST_HEADER_NAME = "Authorization";
private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();
private String token;
public static RequestContext getContext() {
RequestContext result = CONTEXT.get();
if (result == null) {
result = new RequestContext();
CONTEXT.set(result);
}
return result;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor{
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
String token = RequestContext.getContext().getToken();
request.getHeaders().add(RequestContext.REQUEST_HEADER_NAME, token);
return execution.execute(request, body);
}
}
class RestTemplateHeaderModifierInterceptor(private val authenticationService: IAuthenticationService) : ClientHttpRequestInterceptor {
override fun intercept(request: org.springframework.http.HttpRequest, body: ByteArray, execution: ClientHttpRequestExecution): ClientHttpResponse {
if (!request.headers.containsKey("Authorization")) {
// don't overwrite, just add if not there.
val jwt = authenticationService.getCurrentUser()!!.jwt
request.headers.add("Authorization", "Bearer $jwt")
}
val response = execution.execute(request, body)
return response
}
}
并将其添加到RestTemplate,如下所示:
@Bean
fun restTemplate(): RestTemplate {
val restTemplate = RestTemplate()
restTemplate.interceptors.add(RestTemplateHeaderModifierInterceptor(authenticationService)) // add interceptor to send JWT along with requests.
return restTemplate
}
val details = SecurityContextHolder.getContext().authentication.details
if (details is OAuth2AuthenticationDetails) {
val token = tokenStore.readAccessToken(details.tokenValue)
return token.value
}
4条答案
按热度按时间6vl6ewon1#
基本上,您的令牌应该位于请求的头部,例如:授权:要获取它,您可以通过控制器中的@RequestHeader()获取任何头值:
现在,您可以将令牌放在以下请求的标头中:
现在可以将HttpEntity传递给rest模板了:
希望我能帮忙
cwtwac6a2#
我已完成任务,创建了自定义筛选器
然后,在我的配置中设置
考虑到这一点,我创建了另一个带有ThreadLocal变量的类,用于将JWT令牌从控制器传递到Rest Templace拦截器
}
将拦截器添加到配置中
mec1mxoz3#
我认为最好将拦截器专门添加到RestTemplate中,如下所示:
并将其添加到RestTemplate,如下所示:
这样,每次需要RestTemplate时,只需使用自动装配即可获得它。您确实需要实现AuthenticationService,才能从TokenStore获得令牌,如下所示:
wf82jlnq4#
可能有点晚了,但我认为这是一个常见的问题,关于Web客户端的Spring Security 6.0.0,有一个名为
ServletBearerExchangeFilterFunction
的类,您可以使用它从安全上下文读取令牌并注入它。对于
RestTemplate
,没有自动方式,建议使用过滤器