# 授权赠款支助

## 授权代码

|   |有关[授权代码](https://tools.ietf.org/html/rfc6749#section-1.3.1)授权的更多详细信息，请参阅OAuth2.0授权框架。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 获得授权

|   |请参阅[授权请求/回应](https://tools.ietf.org/html/rfc6749#section-4.1.1)协议流以获得授权代码授权。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------|

### 发起授权请求

`OAuth2AuthorizationRequestRedirectFilter`使用`OAuth2AuthorizationRequestResolver`解析`OAuth2AuthorizationRequest`，并通过将最终用户的用户代理重定向到授权服务器的授权端点来启动授权代码授予流。

`OAuth2AuthorizationRequestResolver`的主要作用是从提供的Web请求中解析`OAuth2AuthorizationRequest`。默认实现`DefaultOAuth2AuthorizationRequestResolver`在（默认）路径`/oauth2/authorization/{registrationId}`上匹配，提取`registrationId`并使用它为关联的`OAuth2AuthorizationRequest`构建`OAuth2AuthorizationRequest`。

给出了OAuth2.0客户端注册的以下 Spring Boot2.x属性：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/authorized/okta"
            scope: read, write
        provider:
          okta:
            authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
```

具有基本路径`/oauth2/authorization/okta`的请求将启动由`OAuth2AuthorizationRequestRedirectFilter`重定向的授权请求，并最终启动授权代码授予流。

|   |`AuthorizationCodeOAuth2AuthorizedClientProvider`是用于授权代码授予的`OAuth2AuthorizedClientProvider`的实现，<br/>还通过`OAuth2AuthorizationRequestRedirectFilter`发起重定向的授权请求。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

如果OAuth2.0客户端是[公共客户](https://tools.ietf.org/html/rfc6749#section-2.1)，则按照以下方式配置OAuth2.0客户端注册：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-authentication-method: none
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/authorized/okta"
            ...
```

使用[代码交换的证明密钥](https://tools.ietf.org/html/rfc7636)支持公共客户端。如果客户机运行在不受信任的环境中（例如，本地应用程序或基于Web浏览器的应用程序），因此不能维护其凭据的机密性，则当以下条件成立时，将自动使用PKCE:

1. `client-secret`省略（或为空）

2. `client-authentication-method`设置为“无”（`ClientAuthenticationMethod.NONE`）

`DefaultOAuth2AuthorizationRequestResolver`还支持`URI`使用`UriComponentsBuilder`的`redirect-uri`模板变量。

以下配置使用了所有受支持的`URI`模板变量：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            ...
            redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
            ...
```

|   |`{baseUrl}`解析为`{baseScheme}://{baseHost}{basePort}{basePath}`|
|---|-----------------------------------------------------------------------|

当OAuth2.0客户端运行在[代理服务器](../../../features/exploits/http.html#http-proxy-server)后面时，使用`URI`模板变量配置`redirect-uri`模板变量特别有用。这确保了在展开`redirect-uri`时使用`X-Forwarded-*`头。

### 自定义授权请求

`OAuth2AuthorizationRequestResolver`可以实现的主要用例之一是，能够使用OAuth2.0授权框架中定义的标准参数之上的附加参数来定制授权请求。

例如，OpenID Connect为[授权代码流](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest)定义了额外的OAuth2.0请求参数，它是从[OAuth2.0授权框架](https://tools.ietf.org/html/rfc6749#section-4.1.1)中定义的标准参数扩展而来的。其中一个扩展参数是`prompt`参数。

|   |可选的。以空格分隔、区分大小写的ASCII字符串值列表，该列表指定授权服务器是否提示最终用户进行重新身份验证和同意。定义的值是：none、login、consent、select\_account|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

下面的示例展示了如何使用`DefaultOAuth2AuthorizationRequestResolver`配置`Consumer<OAuth2AuthorizationRequest.Builder>`，该配置通过包括请求参数`oauth2Login()`来定制`oauth2Login()`的授权请求。

Java

```
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests(authorize -> authorize
				.anyRequest().authenticated()
			)
			.oauth2Login(oauth2 -> oauth2
				.authorizationEndpoint(authorization -> authorization
					.authorizationRequestResolver(
						authorizationRequestResolver(this.clientRegistrationRepository)
					)
				)
			);
	}

	private OAuth2AuthorizationRequestResolver authorizationRequestResolver(
			ClientRegistrationRepository clientRegistrationRepository) {

		DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver =
				new DefaultOAuth2AuthorizationRequestResolver(
						clientRegistrationRepository, "/oauth2/authorization");
		authorizationRequestResolver.setAuthorizationRequestCustomizer(
				authorizationRequestCustomizer());

		return  authorizationRequestResolver;
	}

	private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
		return customizer -> customizer
					.additionalParameters(params -> params.put("prompt", "consent"));
	}
}
```

Kotlin

```
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    private lateinit var customClientRegistrationRepository: ClientRegistrationRepository

    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2Login {
                authorizationEndpoint {
                    authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
                }
            }
        }
    }

    private fun authorizationRequestResolver(
            clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver? {
        val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver(
                clientRegistrationRepository, "/oauth2/authorization")
        authorizationRequestResolver.setAuthorizationRequestCustomizer(
                authorizationRequestCustomizer())
        return authorizationRequestResolver
    }

    private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
        return Consumer { customizer ->
            customizer
                    .additionalParameters { params -> params["prompt"] = "consent" }
        }
    }
}
```

对于简单的用例，如果附加的请求参数对于特定的提供者总是相同的，那么可以直接在`authorization-uri`属性中添加它。

例如，如果请求参数`prompt`的值对于提供程序`okta`总是`consent`，那么只需配置如下：

```
spring:
  security:
    oauth2:
      client:
        provider:
          okta:
            authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
```

前面的示例展示了在标准参数之上添加一个自定义参数的常见用例。或者，如果你的需求更高级，那么你可以通过简单地覆盖`OAuth2AuthorizationRequest.authorizationRequestUri`属性来完全控制构建授权请求URI。

|   |`OAuth2AuthorizationRequest.Builder.build()`构造`OAuth2AuthorizationRequest.authorizationRequestUri`，它表示授权请求URI，包括使用`application/x-www-form-urlencoded`格式的所有查询参数。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

下面的示例显示了来自前面示例的`authorizationRequestCustomizer()`的变体，并覆盖了`OAuth2AuthorizationRequest.authorizationRequestUri`属性。

Java

```
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
	return customizer -> customizer
				.authorizationRequestUri(uriBuilder -> uriBuilder
					.queryParam("prompt", "consent").build());
}
```

Kotlin

```
private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
    return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
        customizer
                .authorizationRequestUri { uriBuilder: UriBuilder ->
                    uriBuilder
                            .queryParam("prompt", "consent").build()
                }
    }
}
```

### 存储授权请求

从发起授权请求到接收授权响应（回调），`AuthorizationRequestRepository`负责`OAuth2AuthorizationRequest`的持久性。

|   |`OAuth2AuthorizationRequest`用于关联和验证授权响应。|
|---|----------------------------------------------------------------------------------------------|

`AuthorizationRequestRepository`的默认实现是`HttpSessionOAuth2AuthorizationRequestRepository`，它将`OAuth2AuthorizationRequest`存储在`HttpSession`中。

如果你有`AuthorizationRequestRepository`的自定义实现，则可以按照以下示例对其进行配置：

例1. AuthorizationRequestRepository配置

Java

```
@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationCodeGrant(codeGrant -> codeGrant
					.authorizationRequestRepository(this.authorizationRequestRepository())
					...
				)
			);
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    authorizationRequestRepository = authorizationRequestRepository()
                }
            }
        }
    }
}
```

XML

```
<http>
	<oauth2-client>
		<authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
	</oauth2-client>
</http>
```

### 请求访问令牌

|   |请参阅[访问令牌请求/响应](https://tools.ietf.org/html/rfc6749#section-4.1.3)协议流以获得授权代码授权。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------|

对于授权代码授予，`OAuth2AccessTokenResponseClient`的默认实现是`DefaultAuthorizationCodeTokenResponseClient`，它使用`RestOperations`在授权服务器的令牌端点将授权代码交换为访问令牌。

`DefaultAuthorizationCodeTokenResponseClient`非常灵活，因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

### 自定义访问令牌请求

如果需要定制令牌请求的预处理，则可以提供带有自定义`DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()`的`Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>>`。默认的实现`OAuth2AuthorizationCodeGrantRequestEntityConverter`构建了标准`RequestEntity`表示法[OAuth2.0访问令牌请求](https://tools.ietf.org/html/rfc6749#section-4.1.3)。但是，提供一个自定义`Converter`，将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数，可以为`OAuth2AuthorizationCodeGrantRequestEntityConverter.setParametersConverter()`提供自定义的`Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>`，以完全覆盖随请求发送的参数。这通常比直接构造`RequestEntity`更简单。

|   |如果你只喜欢添加额外的参数，那么可以为`OAuth2AuthorizationCodeGrantRequestEntityConverter.addParametersConverter()`提供一个自定义的`Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>`，它构造一个聚合`Converter`。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |自定义`Converter`必须返回一个OAuth2.0访问令牌请求的有效`RequestEntity`表示，该请求被预期的OAuth2.0提供程序理解。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 自定义访问令牌响应

在另一端，如果需要自定义令牌响应的后处理，则需要为`DefaultAuthorizationCodeTokenResponseClient.setRestOperations()`提供自定义配置的`RestOperations`。默认的`RestOperations`配置如下：

Java

```
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
```

Kotlin

```
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
```

|   |Spring 在发送OAuth2.0访问令牌请求时，需要使用MVC。|
|---|---------------------------------------------------------------------------------------------------------------|

`OAuth2AccessTokenResponseHttpMessageConverter`是用于OAuth2.0访问令牌响应的`HttpMessageConverter`。你可以为`OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()`提供一个自定义的`Converter<Map<String, Object>, OAuth2AccessTokenResponse>`，用于将OAuth2.0访问令牌响应参数转换为`OAuth2AccessTokenResponse`。

`OAuth2ErrorResponseErrorHandler`是一个`ResponseErrorHandler`，它可以处理OAuth2.0错误，例如400BAD请求。它使用`OAuth2ErrorHttpMessageConverter`将OAuth2.0错误参数转换为`OAuth2Error`。

无论你是自定义`DefaultAuthorizationCodeTokenResponseClient`还是提供你自己的`OAuth2AccessTokenResponseClient`实现，你都需要对其进行配置，如以下示例所示：

例2.访问令牌响应配置

Java

```
@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationCodeGrant(codeGrant -> codeGrant
					.accessTokenResponseClient(this.accessTokenResponseClient())
					...
				)
			);
	}
}
```

Kotlin

```
@EnableWebSecurity
class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    accessTokenResponseClient = accessTokenResponseClient()
                }
            }
        }
    }
}
```

XML

```
<http>
	<oauth2-client>
		<authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
	</oauth2-client>
</http>
```

## 刷新令牌

|   |有关[刷新令牌](https://tools.ietf.org/html/rfc6749#section-1.5)的更多详细信息，请参阅OAuth2.0授权框架。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------|

### 刷新访问令牌

|   |请参阅[访问令牌请求/响应](https://tools.ietf.org/html/rfc6749#section-6)协议流以获取刷新令牌授权。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------|

用于刷新令牌授权的`OAuth2AccessTokenResponseClient`的默认实现是`DefaultRefreshTokenTokenResponseClient`，当在授权服务器的令牌端点刷新访问令牌时，它使用`RestOperations`。

`DefaultRefreshTokenTokenResponseClient`非常灵活，因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

### 自定义访问令牌请求

如果需要对令牌请求的预处理进行自定义，则可以提供带有自定义`DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()`的`Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>>`。默认的实现`OAuth2RefreshTokenGrantRequestEntityConverter`构建了标准`RequestEntity`表示法[OAuth2.0访问令牌请求](https://tools.ietf.org/html/rfc6749#section-6)。但是，提供一个自定义`Converter`，将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数，可以为`OAuth2RefreshTokenGrantRequestEntityConverter.setParametersConverter()`提供自定义的`Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>`，以完全覆盖随请求发送的参数。这通常比直接构造`RequestEntity`更简单。

|   |如果你只喜欢添加额外的参数，那么可以为`OAuth2RefreshTokenGrantRequestEntityConverter.addParametersConverter()`提供一个自定义的`Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>`，它构造一个聚合`Converter`。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |自定义`Converter`必须返回一个OAuth2.0访问令牌请求的有效`RequestEntity`表示，该请求被预期的OAuth2.0提供程序理解。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 自定义访问令牌响应

在另一端，如果需要自定义令牌响应的后处理，则需要为`DefaultRefreshTokenTokenResponseClient.setRestOperations()`提供自定义配置的`RestOperations`。默认的`RestOperations`配置如下：

Java

```
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
```

Kotlin

```
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
```

|   |Spring 在发送OAuth2.0访问令牌请求时，需要使用MVC。|
|---|---------------------------------------------------------------------------------------------------------------|

`OAuth2AccessTokenResponseHttpMessageConverter`是用于OAuth2.0访问令牌响应的`HttpMessageConverter`。你可以为`OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()`提供一个自定义`Converter<Map<String, Object>, OAuth2AccessTokenResponse>`，用于将OAuth2.0访问令牌响应参数转换为`OAuth2AccessTokenResponse`。

`OAuth2ErrorResponseErrorHandler`是一个`ResponseErrorHandler`，它可以处理OAuth2.0错误，例如400BAD请求。它使用`OAuth2ErrorHttpMessageConverter`将OAuth2.0错误参数转换为`OAuth2Error`。

无论你是自定义`DefaultRefreshTokenTokenResponseClient`还是提供你自己的`OAuth2AccessTokenResponseClient`实现，你都需要对其进行配置，如以下示例所示：

Java

```
// Customize
OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.authorizationCode()
				.refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
```

Kotlin

```
// Customize
val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .authorizationCode()
        .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
```

|   |`OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()`配置`RefreshTokenOAuth2AuthorizedClientProvider`，<br/>，这是用于刷新令牌授权的`OAuth2AuthorizedClientProvider`的实现。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

`OAuth2RefreshToken`可选地在用于`authorization_code`和`password`授予类型的访问令牌响应中返回。如果`OAuth2AuthorizedClient.getRefreshToken()`可用，而`OAuth2AuthorizedClient.getAccessToken()`过期，则`RefreshTokenOAuth2AuthorizedClientProvider`将自动刷新。

## 客户凭据

|   |有关[客户凭据](https://tools.ietf.org/html/rfc6749#section-1.3.4)授权的更多详细信息，请参阅OAuth2.0授权框架。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 请求访问令牌

|   |请参阅[访问令牌请求/响应](https://tools.ietf.org/html/rfc6749#section-4.4.2)协议流以获取客户端凭据授权。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------|

对于客户端凭据授予，`OAuth2AccessTokenResponseClient`的默认实现是`DefaultClientCredentialsTokenResponseClient`，当在授权服务器的令牌端点请求访问令牌时，它使用`RestOperations`。

`DefaultClientCredentialsTokenResponseClient`非常灵活，因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

### 自定义访问令牌请求

如果需要定制令牌请求的预处理，则可以提供带有自定义`DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()`的`Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>>`。默认的实现`OAuth2ClientCredentialsGrantRequestEntityConverter`构建了标准`RequestEntity`表示法[OAuth2.0访问令牌请求](https://tools.ietf.org/html/rfc6749#section-4.4.2)。但是，提供一个自定义`Converter`，将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数，可以为`OAuth2ClientCredentialsGrantRequestEntityConverter.setParametersConverter()`提供自定义的`Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>`，以完全覆盖随请求发送的参数。这通常比直接构造`RequestEntity`更简单。

|   |如果你只喜欢添加额外的参数，那么可以为`OAuth2ClientCredentialsGrantRequestEntityConverter.addParametersConverter()`提供一个自定义的`Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>`，它构造一个聚合`Converter`。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |自定义`Converter`必须返回一个OAuth2.0访问令牌请求的有效`RequestEntity`表示，该请求被预期的OAuth2.0提供程序理解。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 自定义访问令牌响应

在另一端，如果需要自定义令牌响应的后处理，则需要为`DefaultClientCredentialsTokenResponseClient.setRestOperations()`提供自定义配置的`RestOperations`。默认的`RestOperations`配置如下：

Java

```
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
```

Kotlin

```
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
```

|   |Spring 在发送OAuth2.0访问令牌请求时，需要使用MVC。|
|---|---------------------------------------------------------------------------------------------------------------|

`OAuth2AccessTokenResponseHttpMessageConverter`是用于OAuth2.0访问令牌响应的`HttpMessageConverter`。你可以为`OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()`提供一个自定义的`Converter<Map<String, Object>, OAuth2AccessTokenResponse>`，用于将OAuth2.0访问令牌响应参数转换为`OAuth2AccessTokenResponse`。

`OAuth2ErrorResponseErrorHandler`是一个`ResponseErrorHandler`，它可以处理OAuth2.0错误，例如400BAD请求。它使用`OAuth2ErrorHttpMessageConverter`将OAuth2.0错误参数转换为`OAuth2Error`。

无论你是自定义`DefaultClientCredentialsTokenResponseClient`还是提供你自己的`OAuth2AccessTokenResponseClient`实现，你都需要对其进行配置，如以下示例所示：

Java

```
// Customize
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
```

Kotlin

```
// Customize
val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
```

|   |`OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()`配置`ClientCredentialsOAuth2AuthorizedClientProvider`，<br/>，这是用于客户端凭据授权的`OAuth2AuthorizedClientProvider`的实现。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 使用访问令牌

给出了用于OAuth2.0客户端注册的以下 Spring Boot2.x属性：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: client_credentials
            scope: read, write
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
```

…和`OAuth2AuthorizedClientManager``@Bean`:

Java

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

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.clientCredentials()
					.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()
            .clientCredentials()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}
```

你可以按以下方式获得`OAuth2AccessToken`:

Java

```
@Controller
public class OAuth2ClientController {

	@Autowired
	private OAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/")
	public String index(Authentication authentication,
						HttpServletRequest servletRequest,
						HttpServletResponse servletResponse) {

		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(authentication)
				.attributes(attrs -> {
					attrs.put(HttpServletRequest.class.getName(), servletRequest);
					attrs.put(HttpServletResponse.class.getName(), servletResponse);
				})
				.build();
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);

		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

		return "index";
	}
}
```

Kotlin

```
class OAuth2ClientController {

    @Autowired
    private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager

    @GetMapping("/")
    fun index(authentication: Authentication?,
              servletRequest: HttpServletRequest,
              servletResponse: HttpServletResponse): String {
        val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(authentication)
                .attributes(Consumer { attrs: MutableMap<String, Any> ->
                    attrs[HttpServletRequest::class.java.name] = servletRequest
                    attrs[HttpServletResponse::class.java.name] = servletResponse
                })
                .build()
        val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
        val accessToken: OAuth2AccessToken = authorizedClient.accessToken

        ...

        return "index"
    }
}
```

|   |`HttpServletRequest`和`HttpServletResponse`都是可选属性。<br/>如果不提供，它将默认为`ServletRequestAttributes`使用`RequestContextHolder.getRequestAttributes()`。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## 资源所有者密码凭据

|   |有关[资源所有者密码凭据](https://tools.ietf.org/html/rfc6749#section-1.3.3)授权的更多详细信息，请参阅OAuth2.0授权框架。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 请求访问令牌

|   |请参阅[访问令牌请求/响应](https://tools.ietf.org/html/rfc6749#section-4.3.2)协议流以获取资源所有者密码凭据授权。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|

对于资源所有者密码凭据授予，`OAuth2AccessTokenResponseClient`的默认实现是`DefaultPasswordTokenResponseClient`，当在授权服务器的令牌端点请求访问令牌时，它使用`RestOperations`。

`DefaultPasswordTokenResponseClient`非常灵活，因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

### 自定义访问令牌请求

如果需要定制令牌请求的预处理，则可以提供带有自定义`DefaultPasswordTokenResponseClient.setRequestEntityConverter()`的`Converter<OAuth2PasswordGrantRequest, RequestEntity<?>>`。默认的实现`OAuth2PasswordGrantRequestEntityConverter`构建了标准`RequestEntity`表示法[OAuth2.0访问令牌请求](https://tools.ietf.org/html/rfc6749#section-4.3.2)。但是，提供一个自定义`Converter`，将允许你扩展标准令牌请求并添加自定义参数。

要仅自定义请求的参数，可以为`OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()`提供自定义的`Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>`，以完全覆盖随请求发送的参数。这通常比直接构造`RequestEntity`更简单。

|   |如果你只喜欢添加额外的参数，那么可以为`OAuth2PasswordGrantRequestEntityConverter.addParametersConverter()`提供一个自定义的`Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>`，它构造一个聚合`Converter`。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |自定义`Converter`必须返回一个OAuth2.0访问令牌请求的有效`RequestEntity`表示，该请求被预期的OAuth2.0提供程序理解。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 自定义访问令牌响应

在另一端，如果需要自定义令牌响应的后处理，则需要为`DefaultPasswordTokenResponseClient.setRestOperations()`提供自定义配置的`RestOperations`。默认的`RestOperations`配置如下：

Java

```
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
```

Kotlin

```
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
```

|   |Spring 在发送OAuth2.0访问令牌请求时，需要使用MVC。|
|---|---------------------------------------------------------------------------------------------------------------|

`OAuth2AccessTokenResponseHttpMessageConverter`是用于OAuth2.0访问令牌响应的`HttpMessageConverter`。你可以为`OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()`提供一个自定义的`Converter<Map<String, Object>, OAuth2AccessTokenResponse>`，用于将OAuth2.0访问令牌响应参数转换为`OAuth2AccessTokenResponse`。

`OAuth2ErrorResponseErrorHandler`是一个`ResponseErrorHandler`，它可以处理OAuth2.0错误，例如400BAD请求。它使用`OAuth2ErrorHttpMessageConverter`将OAuth2.0错误参数转换为`OAuth2Error`。

无论你是自定义`DefaultPasswordTokenResponseClient`还是提供你自己的`OAuth2AccessTokenResponseClient`实现，你都需要对其进行配置，如以下示例所示：

Java

```
// Customize
OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
				.refreshToken()
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
```

Kotlin

```
val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
        .refreshToken()
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
```

|   |`OAuth2AuthorizedClientProviderBuilder.builder().password()`配置`PasswordOAuth2AuthorizedClientProvider`，<br/>，这是用于资源所有者密码凭据授予的`OAuth2AuthorizedClientProvider`的实现。|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 使用访问令牌

给出了用于OAuth2.0客户端注册的以下 Spring Boot2.x属性：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: password
            scope: read, write
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
```

…和`OAuth2AuthorizedClientManager``@Bean`:

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 = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
        val password = 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
    }
}
```

你可以按以下方式获得`OAuth2AccessToken`:

Java

```
@Controller
public class OAuth2ClientController {

	@Autowired
	private OAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/")
	public String index(Authentication authentication,
						HttpServletRequest servletRequest,
						HttpServletResponse servletResponse) {

		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(authentication)
				.attributes(attrs -> {
					attrs.put(HttpServletRequest.class.getName(), servletRequest);
					attrs.put(HttpServletResponse.class.getName(), servletResponse);
				})
				.build();
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);

		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

		return "index";
	}
}
```

Kotlin

```
@Controller
class OAuth2ClientController {
    @Autowired
    private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager

    @GetMapping("/")
    fun index(authentication: Authentication?,
              servletRequest: HttpServletRequest,
              servletResponse: HttpServletResponse): String {
        val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(authentication)
                .attributes(Consumer {
                    it[HttpServletRequest::class.java.name] = servletRequest
                    it[HttpServletResponse::class.java.name] = servletResponse
                })
                .build()
        val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
        val accessToken: OAuth2AccessToken = authorizedClient.accessToken

        ...

        return "index"
    }
}
```

|   |`HttpServletRequest`和`HttpServletResponse`都是可选属性。<br/>如果不提供，它将默认为`ServletRequestAttributes`使用`RequestContextHolder.getRequestAttributes()`。|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## JWT持有人

|   |有关[JWT Bearer](https://datatracker.ietf.org/doc/html/rfc7523)授权的更多详细信息，请参考JSON Web Token配置文件获得OAuth2.0客户端身份验证和授权授权。|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 请求访问令牌

|   |请参阅[访问令牌请求/响应](https://datatracker.ietf.org/doc/html/rfc7523#section-2.1)协议流获得JWT承载授权。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------|

对于JWT承载授权，`OAuth2AccessTokenResponseClient`的默认实现是`DefaultJwtBearerTokenResponseClient`，当在授权服务器的令牌端点请求访问令牌时，它使用`RestOperations`。

`DefaultJwtBearerTokenResponseClient`非常灵活，因为它允许你定制令牌请求的预处理和/或令牌响应的后处理。

### 自定义访问令牌请求

如果需要对令牌请求的预处理进行自定义，则可以提供带有自定义`DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()`的`Converter<JwtBearerGrantRequest, RequestEntity<?>>`。默认的实现`JwtBearerGrantRequestEntityConverter`构建了`RequestEntity`表示[OAuth2.0访问令牌请求](https://datatracker.ietf.org/doc/html/rfc7523#section-2.1)。但是，提供一个自定义`Converter`，将允许你扩展令牌请求并添加自定义参数。

要仅自定义请求的参数，可以为`JwtBearerGrantRequestEntityConverter.setParametersConverter()`提供自定义的`Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>`，以完全覆盖随请求发送的参数。这通常比直接构造`RequestEntity`更简单。

|   |如果你只喜欢添加额外的参数，那么可以为`JwtBearerGrantRequestEntityConverter.addParametersConverter()`提供一个自定义的`Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>`，它构造一个聚合`Converter`。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 自定义访问令牌响应

在另一端，如果需要自定义令牌响应的后处理，则需要为`DefaultJwtBearerTokenResponseClient.setRestOperations()`提供自定义配置的`RestOperations`。默认的`RestOperations`配置如下：

Java

```
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
		new FormHttpMessageConverter(),
		new OAuth2AccessTokenResponseHttpMessageConverter()));

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
```

Kotlin

```
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
```

|   |Spring 在发送OAuth2.0访问令牌请求时，需要使用MVC。|
|---|---------------------------------------------------------------------------------------------------------------|

`OAuth2AccessTokenResponseHttpMessageConverter`是用于OAuth2.0访问令牌响应的`HttpMessageConverter`。你可以为`OAuth2AccessTokenResponseHttpMessageConverter.setAccessTokenResponseConverter()`提供一个自定义的`Converter<Map<String, Object>, OAuth2AccessTokenResponse>`，用于将OAuth2.0访问令牌响应参数转换为`OAuth2AccessTokenResponse`。

`OAuth2ErrorResponseErrorHandler`是一个`ResponseErrorHandler`，它可以处理OAuth2.0错误，例如400BAD请求。它使用`OAuth2ErrorHttpMessageConverter`将OAuth2.0错误参数转换为`OAuth2Error`。

无论你是自定义`DefaultJwtBearerTokenResponseClient`还是提供你自己的`OAuth2AccessTokenResponseClient`实现，你都需要对其进行配置，如以下示例所示：

Java

```
// Customize
OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...

JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);

OAuth2AuthorizedClientProvider authorizedClientProvider =
		OAuth2AuthorizedClientProviderBuilder.builder()
				.provider(jwtBearerAuthorizedClientProvider)
				.build();

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
```

Kotlin

```
// Customize
val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...

val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);

val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .provider(jwtBearerAuthorizedClientProvider)
        .build()

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
```

### 使用访问令牌

给出了用于OAuth2.0客户端注册的以下 Spring Boot2.x属性：

```
spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
            authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
            scope: read
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
```

…和`OAuth2AuthorizedClientManager``@Bean`:

Java

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

	JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
			new JwtBearerOAuth2AuthorizedClientProvider();

	OAuth2AuthorizedClientProvider authorizedClientProvider =
			OAuth2AuthorizedClientProviderBuilder.builder()
					.provider(jwtBearerAuthorizedClientProvider)
					.build();

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

	return authorizedClientManager;
}
```

Kotlin

```
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .provider(jwtBearerAuthorizedClientProvider)
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}
```

你可以按以下方式获得`OAuth2AccessToken`:

Java

```
@RestController
public class OAuth2ResourceServerController {

	@Autowired
	private OAuth2AuthorizedClientManager authorizedClientManager;

	@GetMapping("/resource")
	public String resource(JwtAuthenticationToken jwtAuthentication) {
		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
				.principal(jwtAuthentication)
				.build();
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
		OAuth2AccessToken accessToken = authorizedClient.getAccessToken();

		...

	}
}
```

Kotlin

```
class OAuth2ResourceServerController {

    @Autowired
    private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager

    @GetMapping("/resource")
    fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
        val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
                .principal(jwtAuthentication)
                .build()
        val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
        val accessToken: OAuth2AccessToken = authorizedClient.accessToken

        ...

    }
}
```

[核心接口和类](core.html)[OAuth2客户端身份验证](client-authentication.html)