WebClient filter to add Authentication header

10,543

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());
}
Share:
10,543
bpereira
Author by

bpereira

Updated on June 13, 2022

Comments

  • bpereira
    bpereira almost 2 years

    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?

  • FishingIsLife
    FishingIsLife over 3 years
    Can you tell me where the "String token " param comes from ? I mean, we have to include this filter to the Webclient.builder().. stage. So here this parameter is not available right?
  • rieckpil
    rieckpil over 3 years
    Instead of hardcoding a token when creating your WebClient with the builder, you can pass a lambda function that delegates to calling your token provider that retrieves the latest token