# 核心接口/类

## 客户登记

`ClientRegistration`是在 OAuth2.0 或 OpenID Connect1.0 提供程序中注册的客户端的表示。

客户机注册包含信息，例如客户机 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)

		}
	}
}
```

|**1** |`registrationId`:唯一标识`ClientRegistration`的 ID。|
|------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2** |`clientId`:客户端标识符。|
|**3** |`clientSecret`:客户端秘密。|
|**4** |`clientAuthenticationMethod`:用于与提供程序验证客户端的方法。<br/>支持的值是**客户端 \_Secret\_BASIC **，**客户端 \_Secret\_post **，**Private\_Key\_JWT **，**客户端 \_Secret\_JWT **和**无**[（公众客户）](https://tools.ietf.org/html/rfc6749#section-2.1)。|
|**5** |`authorizationGrantType`:OAuth2.0 授权框架定义了四个[授权授予](https://tools.ietf.org/html/rfc6749#section-1.3)类型。<br/>支持的值是`authorization_code`，`client_credentials`，`password`，以及，扩展授权类型`urn:ietf:params:oauth:grant-type:jwt-bearer`。|
|**6** |`redirectUri`:客户端注册的重定向 URI，在最终用户对客户端进行了身份验证和授权访问之后，*授权服务器*将最终用户的用户代理<br/>重定向到该 URI。|
|**7** |`scopes`:客户端在授权请求流期间请求的范围，例如 OpenID、电子邮件或配置文件。|
|**8** |`clientName`:用于客户机的描述性名称。<br/>该名称可用于某些场景，例如在自动生成的登录页面中显示客户机的名称时。|
|**9** |`authorizationUri`:授权服务器的授权端点 URI。|
|**10**|`tokenUri`:授权服务器的令牌端点 URI。|
|**11**|`jwkSetUri`:用于从授权服务器检索[JSON Web Key ](https://tools.ietf.org/html/rfc7517)集的 URI，<br/>，其中包含用于验证 ID 令牌的[JSON Web 签名](https://tools.ietf.org/html/rfc7515)的加密密钥，以及可选的 userinfo 响应。|
|**12**|`issuerUri`:返回 OpenID Connect1.0 提供程序或 OAuth2.0 授权服务器的发行者标识符 URI。|
|**13**|`configurationMetadata`:[OpenID 提供者配置信息](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig).<br/>只有在配置了 Spring boot2.x 属性`spring.security.oauth2.client.provider.[providerId].issuerUri`时，该信息才可用。|
|**14**|`(userInfoEndpoint)uri`:用于访问经过身份验证的最终用户的声明/属性的 userinfo 端点 URI。|
|**15**|`(userInfoEndpoint)authenticationMethod`:向 UserInfo 端点发送访问令牌时使用的身份验证方法。<br/>支持的值是**页眉**、**形式**和**查询**。|
|**16**|`userNameAttributeName`:在引用最终用户的名称或标识符的 UserInfo 响应中返回的属性的名称。|

可以使用发现 OpenID Connect 提供者的[配置端点](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)或授权服务器的[元数据端点](https://tools.ietf.org/html/rfc8414#section-3)来初始配置`ClientRegistration`。

`ClientRegistrations`以这种方式为配置`ClientRegistration`提供了方便的方法，如下例所示：

爪哇

```
ClientRegistration clientRegistration =
	ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build();
```

Kotlin

```
val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build()
```

上面的代码将在系列`[https://idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)`中查询，然后`[https://idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)`，最后是`[https://idp.example.com/.well-known/oauth-authorization-server/issuer](https://idp.example.com/.well-known/oauth-authorization-server/issuer)`，在第一次停止时返回 200 响应。

作为一种替代方法，你可以使用`ClientRegistrations.fromOidcIssuerLocation()`仅查询 OpenID Connect 提供者的配置端点。

## 重新激活注册存储库

`ReactiveClientRegistrationRepository`充当 OAuth2.0/OpenID Connect1.0`ClientRegistration`（s）的存储库。

|   |客户端注册信息最终由关联的授权服务器存储和拥有。<br/>此存储库提供检索主客户端注册信息的子集的能力，该子集与授权服务器一起存储。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Spring Boot2.x Auto-Configuration 将`spring.security.oauth2.client.registration.*[registrationId]*`下的每个属性绑定到`ClientRegistration`的一个实例，然后在`ClientRegistration`中组合每个`ClientRegistration`实例。

|   |`ReactiveClientRegistrationRepository`的默认实现是`InMemoryReactiveClientRegistrationRepository`。|
|---|-----------------------------------------------------------------------------------------------------------------------|

自动配置还在`ApplicationContext`中将`ReactiveClientRegistrationRepository`注册为`@Bean`，以便在应用程序需要时可用于依赖注入。

下面的清单展示了一个示例：

爪哇

```
@Controller
public class OAuth2ClientController {

	@Autowired
	private ReactiveClientRegistrationRepository clientRegistrationRepository;

	@GetMapping("/")
	public Mono<String> index() {
		return this.clientRegistrationRepository.findByRegistrationId("okta")
				...
				.thenReturn("index");
	}
}
```

Kotlin

```
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository

    @GetMapping("/")
    fun index(): Mono<String> {
        return this.clientRegistrationRepository.findByRegistrationId("okta")
            ...
            .thenReturn("index")
    }
}
```

## OAuth2 授权客户端

`OAuth2AuthorizedClient`是授权客户的表示。当最终用户（资源所有者）已向客户端授予访问其受保护资源的授权时，客户端被视为已被授权。

`OAuth2AuthorizedClient`的目的是将`OAuth2AccessToken`（和可选`OAuth2RefreshToken`）关联到`ClientRegistration`（客户端）和资源所有者，后者是授予授权的`Principal`最终用户。

## serveroauth2authorizedclientpository/reactiveoauth2authorizedclientservice

`ServerOAuth2AuthorizedClientRepository`负责在 Web 请求之间持久化`OAuth2AuthorizedClient`。然而，`ReactiveOAuth2AuthorizedClientService`的主要作用是在应用程序级管理`OAuth2AuthorizedClient`。

从开发人员的角度来看，`ServerOAuth2AuthorizedClientRepository`或`ReactiveOAuth2AuthorizedClientService`提供了查找与客户端关联的`OAuth2AccessToken`的功能，以便可以使用它来发起受保护的资源请求。

下面的清单展示了一个示例：

爪哇

```
@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");
	}
}
```

Kotlin

```
@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 Boot2.x 自动配置在`ApplicationContext`中注册了一个`ServerOAuth2AuthorizedClientRepository`和/或`ReactiveOAuth2AuthorizedClientService``@Bean`。<br/>但是，应用程序可以选择覆盖和注册一个自定义的`ServerOAuth2AuthorizedClientRepository`或`ReactiveOAuth2AuthorizedClientService`。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

`ReactiveOAuth2AuthorizedClientService`的默认实现是`InMemoryReactiveOAuth2AuthorizedClientService`，它在内存中存储`OAuth2AuthorizedClient`。

或者，R2DBC 实现可以被配置为在数据库中持久化。

|   |`R2dbcReactiveOAuth2AuthorizedClientService`取决于[OAuth2.0 客户端模式](../../../servlet/appendix/database-schema.html#dbschema-oauth2-client)中描述的表定义。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## reactiveOAuth2AuthorizedClientManager/reactiveOAuth2AuthorizedClientProvider

`ReactiveOAuth2AuthorizedClientManager`负责`OAuth2AuthorizedClient`（s）的全面管理。

主要职责包括：

* 使用`ReactiveOAuth2AuthorizedClientProvider`对 OAuth2.0 客户端进行授权（或重新授权）。

* 委派`OAuth2AuthorizedClient`的持久性，通常使用`ReactiveOAuth2AuthorizedClientService`或`ServerOAuth2AuthorizedClientRepository`。

* 当一个 OAuth2.0 客户端已被成功授权（或重新授权）时，将其委托给`ReactiveOAuth2AuthorizationSuccessHandler`。

* 当 OAuth2.0 客户端未能授权（或重新授权）时，将其委托给`ReactiveOAuth2AuthorizationFailureHandler`。

`ReactiveOAuth2AuthorizedClientProvider`实现了对 OAuth2.0 客户端进行授权（或重新授权）的策略。实现通常将实现一种授权授予类型，例如。`authorization_code`，`client_credentials`等。

`ReactiveOAuth2AuthorizedClientManager`的默认实现是`DefaultReactiveOAuth2AuthorizedClientManager`，它与`ReactiveOAuth2AuthorizedClientProvider`相关联，后者可能使用基于委托的组合来支持多个授权授予类型。`ReactiveOAuth2AuthorizedClientProviderBuilder`可用于配置和构建基于委托的组合。

下面的代码展示了如何配置和构建`ReactiveOAuth2AuthorizedClientProvider`组合的示例，该组合为`authorization_code`、`refresh_token`、`client_credentials`和`password`授权授予类型提供支持：

爪哇

```
@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

	ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
			ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
					.authorizationCode()
					.refreshToken()
					.clientCredentials()
					.password()
					.build();

	DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultReactiveOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}
```

Kotlin

```
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ReactiveClientRegistrationRepository,
        authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
    val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build()
    val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}
```

当授权尝试成功时，`DefaultReactiveOAuth2AuthorizedClientManager`将委托给`ReactiveOAuth2AuthorizationSuccessHandler`，该（默认情况下）将通过`OAuth2AuthorizedClient`保存`OAuth2AuthorizedClient`。在重新授权失败的情况下，例如，刷新令牌不再有效，先前保存的`OAuth2AuthorizedClient`将通过`RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler`从`ServerOAuth2AuthorizedClientRepository`中删除。默认行为可以通过`setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler)`和`setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)`进行定制。

`DefaultReactiveOAuth2AuthorizedClientManager`还与类型`Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>>`的`contextAttributesMapper`相关联，它负责将属性从`OAuth2AuthorizeRequest`映射到要与`OAuth2AuthorizationContext`相关联的属性的`Map`。当你需要提供带有 Required（Supported）属性的`ReactiveOAuth2AuthorizedClientProvider`时，这可能是有用的，例如，`PasswordReactiveOAuth2AuthorizedClientProvider`要求资源所有者的`username`和`password`在`OAuth2AuthorizationContext.getAttributes()`中可用。

下面的代码显示了`contextAttributesMapper`的示例：

爪哇

```
@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

	ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
			ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
					.password()
					.refreshToken()
					.build();

	DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
			new DefaultReactiveOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientRepository);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	// Assuming the `username` and `password` 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 username = request.getQueryParams().getFirst(OAuth2ParameterNames.USERNAME);
		String password = request.getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD);
		if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
			contextAttributes = new HashMap<>();

			// `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
			contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
			contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
		}
		return Mono.just(contextAttributes);
	};
}
```

Kotlin

```
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ReactiveClientRegistrationRepository,
        authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager {
    val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .refreshToken()
            .build()
    val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

    // Assuming the `username` and `password` 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 username: String? = request.queryParams.getFirst(OAuth2ParameterNames.USERNAME)
        val password: String? = request.queryParams.getFirst(OAuth2ParameterNames.PASSWORD)
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            contextAttributes = hashMapOf()

            // `PasswordReactiveOAuth2AuthorizedClientProvider` requires both attributes
            contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username!!
            contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password!!
        }
        Mono.just(contextAttributes)
    }
}
```

`DefaultReactiveOAuth2AuthorizedClientManager`被设计用于***内***`ServerWebExchange`的上下文。当操作***外面***的`ServerWebExchange`上下文时，请使用`AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager`。

当使用`AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager`时，*服务应用程序*是一个常见的用例。服务应用程序通常在后台运行，没有任何用户交互，并且通常在系统级帐户而不是用户帐户下运行。配置为`client_credentials`grant 类型的 OAuth2.0 客户机可以被视为服务应用程序的一种类型。

下面的代码展示了如何配置`AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager`的示例，该示例为`client_credentials`grant 类型提供支持：

爪哇

```
@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;
}
```

Kotlin

```
@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
}
```

[OAuth2 客户端](index.html)[OAuth2 授权授予](authorization-grants.html)