英文:
WebClient filter to add Authentication header
问题
我正准备实现一些需要身份验证头的外部服务请求。
身份验证服务是一个外部服务,为了获取令牌,我需要发起一个HTTP调用。
我考虑采用的策略是创建一个附加到WebClient的过滤器,调用该服务以获取令牌,然后将其添加到头部。
当然,我会实现一些缓存层来获取令牌,但重点是我将向我的请求添加一个请求。
您认为这是一个有效的方法吗?还是应该在主请求之外显式调用身份验证服务?
英文:
I'm about to implement a number of requests to external services that require an Authentication header.
The authentication service is an external service and in order to retrieve the Token, I need to make an HTTP call.
The strategy i'm thinking of moving forward with is to create append a filter to WebClient that calls this service to get the token and then add it to the header.
Of course I'm going to implement some caching layer to retrieve the token, but the point is that I'm going to add a request to my request.
Do you think it's a valid approach? Or should I just explicitly call the Authentication Service outside of the main request?
答案1
得分: 4
如果这是OAuth2,并且您需要JWT令牌用于您的请求,Spring Security和WebClient
也能够执行此操作(基于Spring WebFlux的示例,Spring Web示例)。我不会在过滤器中实现此逻辑,而是创建一个WebClient
过滤器,为每个请求设置Authorization: Bearer XYZ
头,并通过Spring从外部或传递令牌。
您还可以查看这个库。它会定期在后台线程中为您获取OAuth2令牌,并将其传递给您的WebClient
。
WebClient
的自定义过滤器可能如下所示:
private ExchangeFilterFunction authHeader(String token) {
return (request, next) -> next.exchange(ClientRequest.from(request).headers(headers -> {
headers.setBearerAuth(token);
}).build());
}
英文:
If it's OAuth2 and you need the JWT token for your request, Spring Security and the WebClient
is also capable of doing this (Spring WebFlux based example, Spring Web example). I wouldn't implement this logic within a filter, rather create a WebClient
filter to set the Authorization: Bearer XYZ
header for each request and pass the token from outside or by Spring.
You can also have a look at this library. It fetches OAuth2 tokens in a background thread regularly for you and you can pass it to your WebClient
.
A custom filter for the WebClient
may look like the following:
private ExchangeFilterFunction authHeader(String token) {
return (request, next) -> next.exchange(ClientRequest.from(request).headers((headers) -> {
headers.setBearerAuth(token);
}).build());
}
答案2
得分: 1
你可以使用来自spring-security-oauth2-resource-server
包的现有ServletBearerExchangeFilterFunction
过滤器。
@Bean
WebClient webClient() {
ServletBearerExchangeFilterFunction bearer = new ServletBearerExchangeFilterFunction();
return WebClient.builder()
.filter(bearer).build();
}
英文:
You can use existing ServletBearerExchangeFilterFunction
filter from spring-security-oauth2-resource-server
package.
@Bean
WebClient webClient() {
ServletBearerExchangeFilterFunction bearer = new ServletBearerExchangeFilterFunction();
return WebClient.builder()
.filter(bearer).build();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论