Search code examples
springspring-bootspring-webfluxspring-annotationsspring-webclient

Why isn't my Spring WebFilter being applied to my webclient API requests?


I am trying to create a WebFilter for my Spring App's web client requests so that a token will be added within the headers of the request. It seems that my WebFilter isn't ever called since the println I've added in the filter is never printed out.

This is my WebFilter

@Component
public class Auth0RequestFilter implements WebFilter {

    @Value("${auth0.audiences}")
    private Set<String> auth0Audiences;
    
    @Autowired
    Auth0Client auth0Client;
    
    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange,
            WebFilterChain webFilterChain) {
        String audience = serverWebExchange.getRequest().getURI().getHost();
        System.out.println("We've reached this piece of code");
        if(auth0Audiences.contains(audience)) {
            String accessToken = auth0Client.getAccessToken(audience);
            serverWebExchange.getRequest().getHeaders().add("authorization", "Bearer ".concat(accessToken));
        }
        return webFilterChain.filter(serverWebExchange);
    }

}

And this is my API request:

@Component
public class TestAPICall {

    final Auth0RequestFilter auth0RequestFilter;

    public TestAPICall(Auth0RequestFilter auth0RequestFilter) {
        this.auth0RequestFilter = auth0RequestFilter;
    }

    WebClient client = WebClient.create();

    @Scheduled(fixedRate = 10000)
    public void scheduleFixedRateTask() {
        client.get()
                .uri("https://google.com")
                .retrieve()
                .bodyToMono(String.class)
                .block();
    }
}

Solution

  • WebFilter is a contract for interception-style, chained processing of server Web requests, not client.

    To intercept client requests you need to use ExchangeFilterFunction

    ExchangeFilterFunction filterFunction = (clientRequest, nextFilter) -> {
        …
        return nextFilter.exchange(clientRequest);
    };
    

    and then add it to the WebClient instance

    WebClient webClient = WebClient.builder()
      .filter(filterFunction)
      .build();