0

This is the error response I get when using WebClient currently

{
  "type": "https://www.jhipster.tech/problem/problem-with-message",
  "title": "Internal Server Error",
  "status": 500,
  "detail": "401 Unauthorized from GET http://localhost:8080/services/user/api/users/1",
  "path": "/api/posts",
  "message": "error.http.500"
}

This is how I am using WebClient

webclient.get().uri(ur).retrieve().bodyToMono(User.class).block();
Kevin
  • 1
  • 1

1 Answers1

1

I assume you have a servlet based application since you are subscribing to the Mono and blocking.

The first step is to configure WebClient with OAuth 2.0 Client support:

@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
    ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
            new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    return WebClient.builder()
            .apply(oauth2Client.oauth2Configuration())
            .build();
}

Then you can set an OAuth2AuthorizedClient as a request attribute:

String body = this.webClient
        .get()
        .attributes(clientRegistrationId("client-id"))
        .retrieve()
        .bodyToMono(String.class)
        .block();

You can find more details in the Spring Security reference documentation.

You can find a full example in the Spring Security samples GitHub repository.