跳到主要内容
版本:7.0.2

HTTP 服务客户端集成

DeepSeek V3 中英对照 HTTP Service Clients HTTP Service Clients Integration

Spring Security 的 OAuth 支持可以与 RestClientWebClient HTTP 服务客户端集成。

配置

在完成 RestClientWebClient 的特定配置后,使用 HTTP 服务客户端集成 仅需在需要 OAuth 的方法或其声明的 HTTP 接口上添加 @ClientRegistrationId 注解。

由于 @ClientRegistrationId 的存在决定了 OAuth 令牌是否以及如何被解析,因此在任何配置中添加 Spring Security 的 OAuth 支持都是安全的。

RestClient 配置

Spring Security 的 OAuth 支持可以与基于 RestClientHTTP 服务客户端集成。第一步是创建一个 OAuthAuthorizedClientManager Bean

接下来,你必须配置 HttpServiceProxyFactoryRestClient,使其能够识别 @ClientRegistrationId。为了简化此配置,请使用 OAuth2RestClientHttpServiceGroupConfigurer

@Bean
OAuth2RestClientHttpServiceGroupConfigurer securityConfigurer(
OAuth2AuthorizedClientManager manager) {
return OAuth2RestClientHttpServiceGroupConfigurer.from(manager);
}

配置:

WebClient 配置

Spring Security 的 OAuth 支持可以与由 WebClient 支持的 HTTP 服务客户端 集成。第一步是 创建一个 ReactiveOAuthAuthorizedClientManager Bean

接下来,你必须配置 HttpServiceProxyFactoryWebRestClient,使其能够识别 @ClientRegistrationId。为了简化此配置,请使用 OAuth2WebClientHttpServiceGroupConfigurer

@Bean
OAuth2WebClientHttpServiceGroupConfigurer securityConfigurer(
ReactiveOAuth2AuthorizedClientManager manager) {
return OAuth2WebClientHttpServiceGroupConfigurer.from(manager);
}

配置:

@ClientRegistrationId

您可以在 HTTP 服务上添加 ClientRegistrationId 来指定要使用的 ClientRegistration

@GetExchange("/user")
@ClientRegistrationId("github")
User getAuthenticatedUser();

类型级声明

@ClientRegistrationId 也可在类型级别添加,以避免在每个方法上重复声明。

@HttpExchange
@ClientRegistrationId("github")
public interface UserService {

@GetExchange("/user")
User getAuthenticatedUser();

@GetExchange("/users/{username}/hovercard")
Hovercard getHovercard(@PathVariable String username);

}

ClientRegistrationIdProcessor

配置好的 ClientRegistrationIdProcessor 将:

随后,id 会经过以下处理: