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)
}
此配置
-
将
OAuth2ClientHttpRequestInterceptor添加到RestClient
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
-
对于每个
@ClientRegistrationId,自动调用ClientAttributes.clientRegistrationId(String)。 -
这将
ClientRegistration.getId()添加到属性中
然后,id 由以下组件处理:
-
用于 RestClient 集成 的
OAuth2ClientHttpRequestInterceptor -
用于
WebClient的ServletOAuth2AuthorizedClientExchangeFilterFunction(Servlet 环境)或ServerOAuth2AuthorizedClientExchangeFilterFunction(响应式环境)。