Issue
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?
Solution
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());
}
Answered By - rieckpil
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)