springspring-bootspring-security

WebClient with DefaultOAuth2AuthorizedClientManager is working for integration test but not for main runtime


I have a WebClient configured as below. In main runtime, webClient is used in a kafka listener started thread. So out of http servlet context. And it is failing as I noticed we should use AuthorizedClientServiceOAuth2AuthorizedClientManager to use it out of http servlet context.

@Bean
WebClient webCient(ClientRegistrationRepository clientRegistrationRepository,
                                     OAuth2AuthorizedClientRepository authorizedClientRepository) {
    var oauth = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository);
    oauth.setDefaultClientRegistrationId("keycloak");
    return WebClient.builder()
            .apply(oauth.oauth2Configuration())
            .baseUrl(properties.getHost())
            .build();
}

However, an isolated integration test directly making a request using webClient and it does not fail as expected servletRequest cannot be null error, since it is used also out of http servlet context (it is not called in the flow of any controllers)

Is it @SpringBootTest initialising some kind of mock http servlet context and during test runtime satisfies the DefaultOAuth2AuthorizedClientManager?


Solution

  • I found the answer here.

    It seems indeed, @SpringBootTest mocks the ServletRequest, so we cannot reproduce the same error in test runtime.