# 核心接口/类

## 客户登记

`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`提供了方便的方法，如下例所示：

Java

```
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提供者的配置端点。

## ClientRegistrationRepository

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

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

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

|   |`ClientRegistrationRepository`的默认实现是`InMemoryClientRegistrationRepository`。|
|---|-------------------------------------------------------------------------------------------------------|

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

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

Java

```
@Controller
public class OAuth2ClientController {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@GetMapping("/")
	public String index() {
		ClientRegistration oktaRegistration =
			this.clientRegistrationRepository.findByRegistrationId("okta");

		...

		return "index";
	}
}
```

Kotlin

```
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var clientRegistrationRepository: ClientRegistrationRepository

    @GetMapping("/")
    fun index(): String {
        val oktaRegistration =
                this.clientRegistrationRepository.findByRegistrationId("okta")

        //...

        return "index";
    }
}
```

## OAuth2授权客户端

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

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

## OAuth2authorizedClientPository/OAuth2authorizedClientService

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

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

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

Java

```
@Controller
public class OAuth2ClientController {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/")
    public String index(Authentication authentication) {
        OAuth2AuthorizedClient authorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());

        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

        ...

        return "index";
    }
}
```

Kotlin

```
@Controller
class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientService: OAuth2AuthorizedClientService

    @GetMapping("/")
    fun index(authentication: Authentication): String {
        val authorizedClient: OAuth2AuthorizedClient =
            this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName());
        val accessToken = authorizedClient.accessToken

        ...

        return "index";
    }
}
```

|   |Spring Boot2.x自动配置在`ApplicationContext`中注册一个`OAuth2AuthorizedClientRepository`和/或`OAuth2AuthorizedClientService``@Bean`。<br/>但是，应用程序可以选择重写并注册一个自定义的`OAuth2AuthorizedClientRepository`或`OAuth2AuthorizedClientService`。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

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

或者，可以将JDBC实现`JdbcOAuth2AuthorizedClientService`配置为在数据库中持久化`OAuth2AuthorizedClient`。

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

## OAuth2AuthorizedClientManager/OAuth2AuthorizedClientProvider

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

主要职责包括：

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

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

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

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

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

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

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

Java

```
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.authorizationCode()
					.refreshToken()
					.clientCredentials()
					.password()
					.build();

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

	return authorizedClientManager;
}
```

Kotlin

```
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .authorizationCode()
            .refreshToken()
            .clientCredentials()
            .password()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}
```

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

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

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

Java

```
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.password()
					.refreshToken()
					.build();

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

	// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
	// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
	authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());

	return authorizedClientManager;
}

private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
	return authorizeRequest -> {
		Map<String, Object> contextAttributes = Collections.emptyMap();
		HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
		String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
		String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
		if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
			contextAttributes = new HashMap<>();

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

Kotlin

```
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .refreshToken()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

    // Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
    // map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
    authorizedClientManager.setContextAttributesMapper(contextAttributesMapper())
    return authorizedClientManager
}

private fun contextAttributesMapper(): Function<OAuth2AuthorizeRequest, MutableMap<String, Any>> {
    return Function { authorizeRequest ->
        var contextAttributes: MutableMap<String, Any> = mutableMapOf()
        val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
        val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
        val password: String = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            contextAttributes = hashMapOf()

            // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
            contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
            contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
        }
        contextAttributes
    }
}
```

`DefaultOAuth2AuthorizedClientManager`被设计用于***内***`HttpServletRequest`的上下文。当操作***外面***的`HttpServletRequest`上下文时，请使用`AuthorizedClientServiceOAuth2AuthorizedClientManager`。

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

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

Java

```
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientService authorizedClientService) {

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.clientCredentials()
					.build();

	AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
			new AuthorizedClientServiceOAuth2AuthorizedClientManager(
					clientRegistrationRepository, authorizedClientService);
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	return authorizedClientManager;
}
```

Kotlin

```
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientService)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}
```

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