简体   繁体   English

带有自定义 OAuth2 请求的 Spring WebClient

[英]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".我正在构建一个应用程序,该应用程序必须与使用 OAuth2 和授权类型 client_credentials 保护的 REST 服务进行通信,问题是 /oauth/token 端点需要自定义标头,为了简化起见,我们将其称为“自定义标头” ”。 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.如您所见,我在 WebClient 中设置了 custome 标头,但它没有到达 oauth 过滤器。

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最后我的解决方案是重新实现 OAuth2ExchangeFilterFunction 并实现我自己的 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.在 CustomWebClientCredentialsTokenResponseClient 中,我添加了提供者期望的自定义​​标头,并且在 createDefaultAuthorizedClientManager() 方法中,我必须创建我创建的 CustomWebClientCredentialsTokenResponseClient 的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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