首页 > 解决方案 > 如何将 OAuth 2.0 不记名令牌添加到 WebClient

问题描述

WebClient这是我当前使用时得到的错误响应

{
  "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"
}

这就是我使用的方式WebClient

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

标签: spring-bootspring-securityspring-webclient

解决方案


我假设您有一个基于 servlet 的应用程序,因为您订阅了Mono和阻塞。

第一步是配置WebClientOAuth 2.0 客户端支持:

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

然后你可以设置一个OAuth2AuthorizedClient作为请求属性:

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

您可以在Spring Security 参考文档中找到更多详细信息。

您可以在Spring Security GitHub 存储库中找到完整示例。


推荐阅读