HTTP 服务客户端集成
Spring Security 的 OAuth 支持可以与 RestClient 和 WebClient HTTP 服务客户端集成。
配置
在完成 RestClient 或 WebClient 的特定配置后,使用 HTTP 服务客户端集成 仅需在需要 OAuth 的方法或其声明的 HTTP 接口上添加 @ClientRegistrationId 注解。
由于 @ClientRegistrationId 的存在决定了 OAuth 令牌是否以及如何被解析,因此在任何配置中添加 Spring Security 的 OAuth 支持都是安全的。
RestClient 配置
Spring Security 的 OAuth 支持可以与基于 RestClient 的 HTTP 服务客户端集成。第一步是创建一个 OAuthAuthorizedClientManager Bean。
接下来,你必须配置 HttpServiceProxyFactory 和 RestClient,使其能够识别 @ClientRegistrationId。为了简化此配置,请使用 OAuth2RestClientHttpServiceGroupConfigurer。
- Java
- Kotlin
@Bean
OAuth2RestClientHttpServiceGroupConfigurer securityConfigurer(
OAuth2AuthorizedClientManager manager) {
return OAuth2RestClientHttpServiceGroupConfigurer.from(manager);
}
@Bean
fun securityConfigurer(manager: OAuth2AuthorizedClientManager): OAuth2RestClientHttpServiceGroupConfigurer {
return OAuth2RestClientHttpServiceGroupConfigurer.from(manager)
}
配置:
-
向
RestClient添加了 OAuth2ClientHttpRequestInterceptor
WebClient 配置
Spring Security 的 OAuth 支持可以与由 WebClient 支持的 HTTP 服务客户端 集成。第一步是 创建一个 ReactiveOAuthAuthorizedClientManager Bean。
接下来,你必须配置 HttpServiceProxyFactory 和 WebRestClient,使其能够识别 @ClientRegistrationId。为了简化此配置,请使用 OAuth2WebClientHttpServiceGroupConfigurer。
- Java
- Kotlin
@Bean
OAuth2WebClientHttpServiceGroupConfigurer securityConfigurer(
ReactiveOAuth2AuthorizedClientManager manager) {
return OAuth2WebClientHttpServiceGroupConfigurer.from(manager);
}
@Bean
fun securityConfigurer(
manager: ReactiveOAuth2AuthorizedClientManager?
): OAuth2WebClientHttpServiceGroupConfigurer {
return OAuth2WebClientHttpServiceGroupConfigurer.from(manager)
}
配置:
@ClientRegistrationId
您可以在 HTTP 服务上添加 ClientRegistrationId 来指定要使用的 ClientRegistration。
- Java
- Kotlin
@GetExchange("/user")
@ClientRegistrationId("github")
User getAuthenticatedUser();
@GetExchange("/user")
@ClientRegistrationId("github")
fun getAuthenticatedUser() : User
类型级声明
@ClientRegistrationId 也可在类型级别添加,以避免在每个方法上重复声明。
- Java
- Kotlin
@HttpExchange
@ClientRegistrationId("github")
public interface UserService {
@GetExchange("/user")
User getAuthenticatedUser();
@GetExchange("/users/{username}/hovercard")
Hovercard getHovercard(@PathVariable String username);
}
@HttpExchange
@ClientRegistrationId("github")
interface UserService {
@GetExchange("/user")
fun getAuthenticatedUser(): User
@GetExchange("/users/{username}/hovercard")
fun getHovercard(@PathVariable username: String): Hovercard
}
ClientRegistrationIdProcessor
配置好的 ClientRegistrationIdProcessor 将:
-
为每个 @ClientRegistrationId 自动调用 ClientAttributes.clientRegistrationId(String)。
-
这会将 ClientRegistration.getId() 添加到属性中
随后,id 会经过以下处理:
-
用于 RestClient 集成 的
OAuth2ClientHttpRequestInterceptor -
用于
WebClient的 ServletOAuth2AuthorizedClientExchangeFilterFunction(Servlet 环境)或 ServerOAuth2AuthorizedClientExchangeFilterFunction(响应式环境)。