核心接口/类
ClientRegistration
ClientRegistration 是一个表示已在 OAuth 2.0 或 OpenID Connect 1.0 Provider 注册的客户端的类。
客户端注册保存了诸如客户端 ID、客户端密钥、授权授予类型、重定向 URI、范围、授权 URI、令牌 URI 和其他详细信息。
ClientRegistration 及其属性定义如下
public final class ClientRegistration {
private String registrationId; (1)
private String clientId; (2)
private String clientSecret; (3)
private ClientAuthenticationMethod clientAuthenticationMethod; (4)
private AuthorizationGrantType authorizationGrantType; (5)
private String redirectUri; (6)
private Set<String> scopes; (7)
private ProviderDetails providerDetails;
private String clientName; (8)
public class ProviderDetails {
private String authorizationUri; (9)
private String tokenUri; (10)
private UserInfoEndpoint userInfoEndpoint;
private String jwkSetUri; (11)
private String issuerUri; (12)
private Map<String, Object> configurationMetadata; (13)
public class UserInfoEndpoint {
private String uri; (14)
private AuthenticationMethod authenticationMethod; (15)
private String userNameAttributeName; (16)
}
}
public static final class ClientSettings {
private boolean requireProofKey; (17)
}
}
| 1 | registrationId:唯一标识 ClientRegistration 的 ID。 |
| 2 | clientId:客户端标识符。 |
| 3 | clientSecret:客户端密钥。 |
| 4 | clientAuthenticationMethod:用于向 Provider 验证客户端的方法。支持的值有 client_secret_basic、client_secret_post、private_key_jwt、client_secret_jwt 和 none (公共客户端)。 |
| 5 | authorizationGrantType:OAuth 2.0 授权框架定义了四种 授权授予 类型。支持的值有 authorization_code、client_credentials,以及扩展授予类型 urn:ietf:params:oauth:grant-type:jwt-bearer。 |
| 6 | redirectUri:客户端注册的重定向 URI,授权服务器 在最终用户认证并授权客户端访问后,会将最终用户的用户代理重定向到该 URI。 |
| 7 | scopes:客户端在授权请求流程中请求的范围,例如 openid、email 或 profile。 |
| 8 | clientName:用于客户端的描述性名称。该名称可能在某些场景中使用,例如在自动生成的登录页面中显示客户端名称。 |
| 9 | authorizationUri:授权服务器的授权端点 URI。 |
| 10 | tokenUri:授权服务器的令牌端点 URI。 |
| 11 | jwkSetUri:用于从授权服务器检索 JSON Web Key (JWK) Set 的 URI,其中包含用于验证 ID 令牌的 JSON Web Signature (JWS) 以及可选的 UserInfo 响应的加密密钥。 |
| 12 | issuerUri:返回 OpenID Connect 1.0 provider 或 OAuth 2.0 Authorization Server 的发行者标识符 URI。 |
| 13 | configurationMetadata:OpenID Provider 配置信息。此信息仅在配置了 Spring Boot 属性 spring.security.oauth2.client.provider.[providerId].issuerUri 时可用。 |
| 14 | (userInfoEndpoint)uri:UserInfo 端点 URI,用于访问已认证最终用户的声明/属性。 |
| 15 | (userInfoEndpoint)authenticationMethod:向 UserInfo 端点发送访问令牌时使用的认证方法。支持的值有 header、form 和 query。 |
| 16 | userNameAttributeName:UserInfo 响应中返回的属性名称,该属性引用最终用户的名称或标识符。 |
| 17 | requireProofKey:如果为 true 或 authorizationGrantType 为 none,则默认启用 PKCE。 |
ClientRegistrations 提供了方便的方法来以这种方式配置 ClientRegistration,如下例所示
-
Java
-
Kotlin
ClientRegistration clientRegistration =
ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();
val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build()
上述代码将依次查询 idp.example.com/issuer/.well-known/openid-configuration,然后是 idp.example.com/.well-known/openid-configuration/issuer,最后是 idp.example.com/.well-known/oauth-authorization-server/issuer,在第一个返回 200 响应时停止。
作为替代,您可以使用 ClientRegistrations.fromOidcIssuerLocation() 仅查询 OpenID Connect Provider 的配置端点。
ReactiveClientRegistrationRepository
ReactiveClientRegistrationRepository 作为 OAuth 2.0 / OpenID Connect 1.0 ClientRegistration 的存储库。
|
客户端注册信息最终由关联的授权服务器存储和拥有。此存储库提供了检索存储在授权服务器中的主要客户端注册信息子集的能力。 |
Spring Boot 自动配置将 spring.security.oauth2.client.registration.[registrationId] 下的每个属性绑定到 ClientRegistration 实例,然后将每个 ClientRegistration 实例组合到 ReactiveClientRegistrationRepository 中。
|
|
自动配置还将 ReactiveClientRegistrationRepository 注册为 ApplicationContext 中的 @Bean,以便应用程序需要时可用于依赖注入。
以下列表显示了一个示例
-
Java
-
Kotlin
@Controller
public class OAuth2ClientController {
@Autowired
private ReactiveClientRegistrationRepository clientRegistrationRepository;
@GetMapping("/")
public Mono<String> index() {
return this.clientRegistrationRepository.findByRegistrationId("okta")
...
.thenReturn("index");
}
}
@Controller
class OAuth2ClientController {
@Autowired
private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository
@GetMapping("/")
fun index(): Mono<String> {
return this.clientRegistrationRepository.findByRegistrationId("okta")
...
.thenReturn("index")
}
}
OAuth2AuthorizedClient
OAuth2AuthorizedClient 是授权客户端的表示。当最终用户(资源所有者)授予客户端访问其受保护资源的授权时,客户端被视为已授权。
OAuth2AuthorizedClient 的目的是将 OAuth2AccessToken(和可选的 OAuth2RefreshToken)与 ClientRegistration(客户端)和资源所有者(授予授权的 Principal 最终用户)关联起来。
ServerOAuth2AuthorizedClientRepository / ReactiveOAuth2AuthorizedClientService
ServerOAuth2AuthorizedClientRepository 负责在 Web 请求之间持久化 OAuth2AuthorizedClient。而 ReactiveOAuth2AuthorizedClientService 的主要作用是在应用程序级别管理 OAuth2AuthorizedClient。
从开发人员的角度来看,ServerOAuth2AuthorizedClientRepository 或 ReactiveOAuth2AuthorizedClientService 提供了查找与客户端关联的 OAuth2AccessToken 的能力,以便将其用于发起受保护的资源请求。
以下列表显示了一个示例
-
Java
-
Kotlin
@Controller
public class OAuth2ClientController {
@Autowired
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
@GetMapping("/")
public Mono<String> index(Authentication authentication) {
return this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName())
.map(OAuth2AuthorizedClient::getAccessToken)
...
.thenReturn("index");
}
}
@Controller
class OAuth2ClientController {
@Autowired
private lateinit var authorizedClientService: ReactiveOAuth2AuthorizedClientService
@GetMapping("/")
fun index(authentication: Authentication): Mono<String> {
return this.authorizedClientService.loadAuthorizedClient<OAuth2AuthorizedClient>("okta", authentication.name)
.map { it.accessToken }
...
.thenReturn("index")
}
}
|
Spring Boot 自动配置在 |
ReactiveOAuth2AuthorizedClientService 的默认实现是 InMemoryReactiveOAuth2AuthorizedClientService,它将 OAuth2AuthorizedClient 存储在内存中。
或者,可以配置 R2DBC 实现 R2dbcReactiveOAuth2AuthorizedClientService 以将 OAuth2AuthorizedClient 持久化到数据库中。
|
|
ReactiveOAuth2AuthorizedClientManager / ReactiveOAuth2AuthorizedClientProvider
ReactiveOAuth2AuthorizedClientManager 负责 OAuth2AuthorizedClient 的整体管理。
主要职责包括
-
使用
ReactiveOAuth2AuthorizedClientProvider授权(或重新授权)OAuth 2.0 客户端。 -
委托
OAuth2AuthorizedClient的持久化,通常使用ReactiveOAuth2AuthorizedClientService或ServerOAuth2AuthorizedClientRepository。 -
当 OAuth 2.0 客户端成功授权(或重新授权)时,委托给
ReactiveOAuth2AuthorizationSuccessHandler。 -
当 OAuth 2.0 客户端授权(或重新授权)失败时,委托给
ReactiveOAuth2AuthorizationFailureHandler。
ReactiveOAuth2AuthorizedClientProvider 实现了授权(或重新授权)OAuth 2.0 客户端的策略。实现通常会实现一种授权授予类型,例如 authorization_code、client_credentials 等。
ReactiveOAuth2AuthorizedClientManager 的默认实现是 DefaultReactiveOAuth2AuthorizedClientManager,它与一个 ReactiveOAuth2AuthorizedClientProvider 相关联,该提供者可以通过基于委托的组合支持多种授权授予类型。ReactiveOAuth2AuthorizedClientProviderBuilder 可用于配置和构建基于委托的组合。
以下代码显示了如何配置和构建一个 ReactiveOAuth2AuthorizedClientProvider 组合,以支持 authorization_code、refresh_token 和 client_credentials 授权授予类型
-
Java
-
Kotlin
@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.build();
DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ReactiveClientRegistrationRepository,
authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.build()
val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}
当授权尝试成功时,DefaultReactiveOAuth2AuthorizedClientManager 将委托给 ReactiveOAuth2AuthorizationSuccessHandler,后者(默认情况下)将通过 ServerOAuth2AuthorizedClientRepository 保存 OAuth2AuthorizedClient。在重新授权失败的情况下,例如刷新令牌不再有效,之前保存的 OAuth2AuthorizedClient 将通过 RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler 从 ServerOAuth2AuthorizedClientRepository 中移除。默认行为可以通过 setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler) 和 setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler) 进行自定义。
DefaultReactiveOAuth2AuthorizedClientManager 还与一个类型为 Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> 的 contextAttributesMapper 相关联,该映射器负责将 OAuth2AuthorizeRequest 中的属性映射到与 OAuth2AuthorizationContext 关联的属性 Map。当您需要向 ReactiveOAuth2AuthorizedClientProvider 提供所需(支持的)属性时,这会很有用。
以下代码显示了 contextAttributesMapper 的示例
-
Java
-
Kotlin
@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Assuming the attributes are supplied as `ServerHttpRequest` parameters,
// map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
return authorizedClientManager;
}
private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper() {
return authorizeRequest -> {
Map<String, Object> contextAttributes = Collections.emptyMap();
ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
ServerHttpRequest request = exchange.getRequest();
String param1 = request.getQueryParams().getFirst("param1");
String param2 = request.getQueryParams().getFirst("param2");
if (StringUtils.hasText(param1) && StringUtils.hasText(param2)) {
contextAttributes = new HashMap<>();
contextAttributes.put("param1", param1);
contextAttributes.put("param2", param2);
}
return Mono.just(contextAttributes);
};
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ReactiveClientRegistrationRepository,
authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build()
val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
// Assuming the attributes are supplied as `ServerHttpRequest` parameters,
// map the `ServerHttpRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
return authorizedClientManager
}
private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, Mono<MutableMap<String, Any>>> {
return Function { authorizeRequest ->
var contextAttributes: MutableMap<String, Any> = mutableMapOf()
val exchange: ServerWebExchange = authorizeRequest.getAttribute(ServerWebExchange::class.java.name)!!
val request: ServerHttpRequest = exchange.request
val param1: String? = request.queryParams.getFirst("param1")
val param2: String? = request.queryParams.getFirst("param2")
if (StringUtils.hasText(param1) && StringUtils.hasText(param2)) {
contextAttributes = hashMapOf()
contextAttributes["param1"] = param1!!
contextAttributes["param2"] = param2!!
}
Mono.just(contextAttributes)
}
}
DefaultReactiveOAuth2AuthorizedClientManager 设计用于 ServerWebExchange 的上下文**中**。当在 ServerWebExchange 上下文**之外**操作时,请改用 AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager。
服务应用程序是使用 AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager 的常见用例。服务应用程序通常在后台运行,没有任何用户交互,并且通常在系统级帐户而不是用户帐户下运行。配置了 client_credentials 授权授予类型的 OAuth 2.0 客户端可以被视为一种服务应用程序。
以下代码显示了如何配置 AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager 以支持 client_credentials 授予类型的示例
-
Java
-
Kotlin
@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ReactiveOAuth2AuthorizedClientService authorizedClientService) {
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials()
.build();
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager =
new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientService);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ReactiveClientRegistrationRepository,
authorizedClientService: ReactiveOAuth2AuthorizedClientService): ReactiveOAuth2AuthorizedClientManager {
val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials()
.build()
val authorizedClientManager = AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientService)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}