Home > Net >  Update authorization header in flux WebClient
Update authorization header in flux WebClient

Time:06-09

I'm trying to create a resilient sse (server sent event) client in reactive programming. The sse endpoint is authenticated, therefore I have to add an authorization header to each request.

The authorization token expires after 1 hour.

Below is a snippet of my code

        webClient.get()
                .uri("/events")
                .headers(httpHeaders -> httpHeaders.setBearerAuth(authService.getIdToken()))
                .retrieve()
                .bodyToFlux(ServerSideEvent.class)
                .timeout(Duration.ofSeconds(TIMEOUT))
                .retryWhen(Retry.fixedDelay(Long.MAX_VALUE, Duration.ofSeconds(RETRY_DELAY)))
                .subscribe(
                        content -> {
                            handleEvent(content);
                        },
                        error -> logger.error("Error receiving SSE: {}", error),
                        () -> logger.info("Completed!!!"));

If after 1 hour the connection is lost for any reason, this code stops working because the token is expired.

How can I refresh the token into the retry logic or in some other way? Thank you

CodePudding user response:

You can use webclient filter.

A filter can intercept and modify client request and response. Example:

WebClient.builder().filter((request, next) -> {
    ClientRequest newReuqest = ClientRequest.from(request)
            .header("Authorization", "YOUR_TOKEN")
            .build();

    return next.exchange(newRequest);
}).build();
  • Related