简体   繁体   中英

Spring WebClient with Custom OAuth2 request

I'm building a app that has to communicate with a REST service that is secured using OAuth2 with grant type client_credentials, the catch is that the /oauth/token endpoint is expecting a custom header, for simplification, let's call it "Custom-Header". My problem is that there is no example or trace in the documentation in how to accomplish this.

My code is as follows

ClientRegistration client = ClientRegistration
                .withRegistrationId(authUser)
                .tokenUri(authUrl)
                .clientId(authUser)
                .clientSecret(authPassword)
                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                .scope(authScope)
                .build();

ReactiveClientRegistrationRepository clientRegistrations =
        new InMemoryReactiveClientRegistrationRepository(client);

ServerOAuth2AuthorizedClientExchangeFilterFunction oauthFilter =
        new ServerOAuth2AuthorizedClientExchangeFilterFunction(
                clientRegistrations,
                new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
oauthFilter.setDefaultClientRegistrationId(authUser);


this.webClient = WebClient.builder()
        .filter(oauthFilter)
        .defaultHeaders(httpHeaders -> {
            httpHeaders.add(CUSTOM_HEADER, customHeader);;
        })
        .build();

As you can see, I'm setting the custome header in the WebClient, but it doesn't reach the oauth filter.

Any help will be appreciated since I've been going back and forth for two days now.

Finally my solution was to reimplment the OAuth2ExchangeFilterFunction and implement my own CustomWebClientCredentialsTokenResponseClient

In CustomWebClientCredentialsTokenResponseClient I added the custom headers that the provider is expecting and in the method createDefaultAuthorizedClientManager() I had to create an instance of the CustomWebClientCredentialsTokenResponseClient I created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM