lealceldeiro/org.wcdevs.blog.core

Add support for client request from the core application

lealceldeiro opened this issue · 1 comments

A new configuration class holding the required beans might be created.
Also there must be a bean of type WebClient ... tentatively this could go like this for a client which performs requests with and authorized token:

 @Bean
  WebClient auothorizedWebClient(ClientRegistrationRepository clientRegistrationRepository,
                            OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository,
                            @Value("${spring.security.oauth2.client.registration.cognito.clientId}") String defaultClientId) {
    // servlet because it's an MVC app
    // if it'd have been a reactive web app, the server flavor should have been used
    var oAuth2clientExFF
        = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository,
                                                                  oAuth2AuthorizedClientRepository);
    oAuth2clientExFF.setDefaultClientRegistrationId(defaultClientId);
    return WebClient.builder().apply(oAuth2clientExFF.oauth2Configuration()).build();
  }

For this to work, the following maven dependency needs to be added:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

And the module-info.java updated like this:

  // ...
  requires spring.webflux;
  requires spring.security.oauth2.client;
  // ...

After that the webclient can be simply injected wheever it's needed

Additionally an unauthorized webclient should be configured for requests where authentication is not required and/or the auth token MUST NOT be sent, like a request to an external service. Something like:

 @Bean
 @Primary
  WebClient webClient() {
    return WebClient.builder().build();
  }