授权授权支持

本节描述 Spring Security 对授权授权的支持。

授权码

有关授权码授权的更多详细信息,请参阅 OAuth 2.0 授权框架 授权码 授权。

获取授权

请参阅授权码授权的授权请求/响应协议流程。

发起授权请求

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

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

考虑 OAuth 2.0 客户端注册的以下 Spring Boot 属性:

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 的实现,它也由 OAuth2AuthorizationRequestRedirectFilter 发起授权请求重定向。

如果 OAuth 2.0 客户端是公共客户端,请按如下方式配置 OAuth 2.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"
            ...

公共客户端支持使用用于代码交换的证明密钥 (PKCE)。如果客户端在不受信任的环境(例如本机应用程序或基于 Web 浏览器的应用程序)中运行,因此无法维护其凭据的机密性,则在满足以下条件时会自动使用 PKCE:

  1. client-secret 被省略(或为空)

  2. client-authentication-method 设置为 noneClientAuthenticationMethod.NONE

如果 OAuth 2.0 提供程序支持机密客户端 的 PKCE,则可以使用 DefaultOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce())(可选)进行配置。

DefaultOAuth2AuthorizationRequestResolver 还支持使用 UriComponentsBuilderredirect-uri 使用 URI 模板变量。

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

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

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

当 OAuth 2.0 客户端运行在代理服务器之后时,使用 URI 模板变量配置 redirect-uri 特别有用。这样做可以确保在扩展 redirect-uri 时使用 X-Forwarded-* 头部。

自定义授权请求

OAuth2AuthorizationRequestResolver 的主要用例之一是能够使用 OAuth 2.0 授权框架中定义的标准参数以外的其他参数来自定义授权请求。

例如,OpenID Connect 为授权码流程定义了额外的 OAuth 2.0 请求参数,这些参数扩展自OAuth 2.0 授权框架中定义的标准参数。其中一个扩展参数是 prompt 参数。

prompt 参数是可选的。空格分隔、区分大小写的 ASCII 字符串值列表,指定授权服务器是否提示最终用户重新进行身份验证和授权。定义的值为:noneloginconsentselect_account

以下示例显示如何使用 Consumer<OAuth2AuthorizationRequest.Builder> 配置 DefaultOAuth2AuthorizationRequestResolver,该消费者通过包含请求参数 prompt=consent 来自定义 oauth2Login() 的授权请求。

  • Java

  • Kotlin

@Configuration
@EnableWebSecurity
public class OAuth2LoginSecurityConfig {

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests(authorize -> authorize
				.anyRequest().authenticated()
			)
			.oauth2Login(oauth2 -> oauth2
				.authorizationEndpoint(authorization -> authorization
					.authorizationRequestResolver(
						authorizationRequestResolver(this.clientRegistrationRepository)
					)
				)
			);
		return http.build();
	}

	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"));
	}
}
@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Autowired
    private lateinit var customClientRegistrationRepository: ClientRegistrationRepository

    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2Login {
                authorizationEndpoint {
                    authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
                }
            }
        }
        return http.build()
    }

    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

  • Kotlin

private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
	return customizer -> customizer
				.authorizationRequestUri(uriBuilder -> uriBuilder
					.queryParam("prompt", "consent").build());
}
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的自定义实现,您可以按如下方式配置它。

AuthorizationRequestRepository 配置
  • Java

  • Kotlin

  • Xml

@Configuration
@EnableWebSecurity
public class OAuth2ClientSecurityConfig {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationCodeGrant(codeGrant -> codeGrant
					.authorizationRequestRepository(this.authorizationRequestRepository())
					...
				)
            .oauth2Login(oauth2 -> oauth2
                .authorizationEndpoint(endpoint -> endpoint
                    .authorizationRequestRepository(this.authorizationRequestRepository())
                    ...
                )
            ).build();
	}

    @Bean
    public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
        return new CustomOAuth2AuthorizationRequestRepository();
    }
}
@Configuration
@EnableWebSecurity
class OAuth2ClientSecurityConfig {

    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    authorizationRequestRepository = authorizationRequestRepository()
                }
            }
        }
        return http.build()
    }
}
<http>
	<oauth2-client>
		<authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
	</oauth2-client>
</http>

请求访问令牌

请参见授权码授予的访问令牌请求/响应协议流程。

授权码授予的OAuth2AccessTokenResponseClient的默认实现是DefaultAuthorizationCodeTokenResponseClient,它使用RestOperations实例在授权服务器的令牌端点交换授权码以获取访问令牌。

DefaultAuthorizationCodeTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。

自定义访问令牌请求

如果您需要自定义令牌请求的预处理,您可以为DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()提供一个自定义的Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>>。默认实现(OAuth2AuthorizationCodeGrantRequestEntityConverter)构建标准OAuth 2.0 访问令牌请求RequestEntity表示。但是,提供自定义Converter可以扩展标准令牌请求并添加自定义参数。

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

如果您只想添加其他参数,您可以为OAuth2AuthorizationCodeGrantRequestEntityConverter.addParametersConverter()提供一个自定义的Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>>,它构建一个聚合的Converter

自定义Converter必须返回目标OAuth 2.0 提供程序可以理解的OAuth 2.0 访问令牌请求的有效RequestEntity表示。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要为DefaultAuthorizationCodeTokenResponseClient.setRestOperations()提供一个自定义配置的RestOperations。默认RestOperations配置如下:

  • Java

  • Kotlin

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

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

需要Spring MVC FormHttpMessageConverter,因为它用于发送OAuth 2.0 访问令牌请求。

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

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,可以处理OAuth 2.0 错误,例如400 Bad Request。它使用OAuth2ErrorHttpMessageConverter将OAuth 2.0 错误参数转换为OAuth2Error

无论您自定义DefaultAuthorizationCodeTokenResponseClient还是提供您自己的OAuth2AccessTokenResponseClient实现,您都需要按如下方式配置它:

访问令牌响应配置
  • Java

  • Kotlin

  • Xml

@Configuration
@EnableWebSecurity
public class OAuth2ClientSecurityConfig {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
			.oauth2Client(oauth2 -> oauth2
				.authorizationCodeGrant(codeGrant -> codeGrant
					.accessTokenResponseClient(this.accessTokenResponseClient())
					...
				)
			);
		return http.build();
	}
}
@Configuration
@EnableWebSecurity
class OAuth2ClientSecurityConfig {

    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            oauth2Client {
                authorizationCodeGrant {
                    accessTokenResponseClient = accessTokenResponseClient()
                }
            }
        }
        return http.build()
    }
}
<http>
	<oauth2-client>
		<authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
	</oauth2-client>
</http>

刷新令牌

有关刷新令牌的更多详细信息,请参阅OAuth 2.0 授权框架。

刷新访问令牌

请参见刷新令牌授权的访问令牌请求/响应协议流程。

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

DefaultRefreshTokenTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理或令牌响应的后处理。

自定义访问令牌请求

如果您需要自定义令牌请求的预处理,您可以为DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()提供一个自定义的Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>>。默认实现(OAuth2RefreshTokenGrantRequestEntityConverter)构建标准OAuth 2.0 访问令牌请求RequestEntity表示。但是,提供自定义Converter可以扩展标准令牌请求并添加自定义参数。

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

如果您只想添加其他参数,您可以为OAuth2RefreshTokenGrantRequestEntityConverter.addParametersConverter()提供一个自定义的Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>>,它构建一个聚合的Converter

自定义Converter必须返回目标OAuth 2.0 提供程序可以理解的OAuth 2.0 访问令牌请求的有效RequestEntity表示。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要为DefaultRefreshTokenTokenResponseClient.setRestOperations()提供一个自定义配置的RestOperations。默认RestOperations配置如下:

  • Java

  • Kotlin

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

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

需要Spring MVC FormHttpMessageConverter,因为它用于发送OAuth 2.0 访问令牌请求。

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

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,可以处理OAuth 2.0 错误,例如400 Bad Request。它使用OAuth2ErrorHttpMessageConverter将OAuth 2.0 错误参数转换为OAuth2Error

无论您自定义DefaultRefreshTokenTokenResponseClient还是提供您自己的OAuth2AccessTokenResponseClient实现,您都需要按如下方式配置它:

  • Java

  • Kotlin

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()配置一个RefreshTokenOAuth2AuthorizedClientProvider,它是刷新令牌授权的OAuth2AuthorizedClientProvider的实现。

OAuth2RefreshToken可以可选地返回authorization_codepassword授予类型的访问令牌响应中。如果OAuth2AuthorizedClient.getRefreshToken()可用并且OAuth2AuthorizedClient.getAccessToken()已过期,则RefreshTokenOAuth2AuthorizedClientProvider会自动刷新它。

客户端凭据

有关客户端凭据授权的更多详细信息,请参阅OAuth 2.0 授权框架。

请求访问令牌

有关客户端凭据授权的更多详细信息,请参阅OAuth 2.0 授权框架。

客户端凭据授权的OAuth2AccessTokenResponseClient的默认实现是DefaultClientCredentialsTokenResponseClient,它在授权服务器的令牌端点请求访问令牌时使用RestOperations

DefaultClientCredentialsTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理或令牌响应的后处理。

自定义访问令牌请求

如果您需要自定义令牌请求的预处理,您可以为DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()提供一个自定义的Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>>。默认实现(OAuth2ClientCredentialsGrantRequestEntityConverter)构建标准OAuth 2.0 访问令牌请求RequestEntity表示。但是,提供自定义Converter可以扩展标准令牌请求并添加自定义参数。

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

如果您只想添加其他参数,您可以为OAuth2ClientCredentialsGrantRequestEntityConverter.addParametersConverter()提供一个自定义的Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>>,它构建一个聚合的Converter

自定义Converter必须返回目标OAuth 2.0 提供程序可以理解的OAuth 2.0 访问令牌请求的有效RequestEntity表示。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要为DefaultClientCredentialsTokenResponseClient.setRestOperations()提供一个自定义配置的RestOperations。默认RestOperations配置如下:

  • Java

  • Kotlin

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

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

需要Spring MVC FormHttpMessageConverter,因为它用于发送OAuth 2.0 访问令牌请求。

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

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,可以处理OAuth 2.0 错误,例如400 Bad Request。它使用OAuth2ErrorHttpMessageConverter将OAuth 2.0 错误参数转换为OAuth2Error

无论您自定义DefaultClientCredentialsTokenResponseClient还是提供您自己的OAuth2AccessTokenResponseClient实现,您都需要按如下方式配置它:

  • Java

  • Kotlin

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()配置一个ClientCredentialsOAuth2AuthorizedClientProvider,它是客户端凭据授权的OAuth2AuthorizedClientProvider的实现。

使用访问令牌

考虑 OAuth 2.0 客户端注册的以下 Spring Boot 属性:

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

  • Kotlin

@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;
}
@Bean
fun authorizedClientManager(
        clientRegistrationRepository: ClientRegistrationRepository,
        authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
    val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
    return authorizedClientManager
}

有了前面的属性和bean,您可以按如下方式获取OAuth2AccessToken

  • Java

  • Kotlin

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

HttpServletRequestHttpServletResponse都是可选属性。如果没有提供,它们将通过使用RequestContextHolder.getRequestAttributes()默认为ServletRequestAttributes

资源所有者密码凭据

有关资源所有者密码凭据授权的更多详细信息,请参阅OAuth 2.0 授权框架。

请求访问令牌

请参见资源所有者密码凭据授权的访问令牌请求/响应协议流程。

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

DefaultPasswordTokenResponseClient非常灵活,因为它允许您自定义令牌请求的预处理或令牌响应的后处理。

自定义访问令牌请求

如果您需要自定义令牌请求的预处理,您可以使用自定义的Converter<OAuth2PasswordGrantRequest, RequestEntity<?>> 提供DefaultPasswordTokenResponseClient.setRequestEntityConverter()。默认实现 (OAuth2PasswordGrantRequestEntityConverter) 会构建标准OAuth 2.0 访问令牌请求RequestEntity 表示。但是,提供自定义的Converter 可以让您扩展标准令牌请求并添加自定义参数。

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

如果您只想添加其他参数,您可以使用自定义的Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> 提供OAuth2PasswordGrantRequestEntityConverter.addParametersConverter(),它会构造一个聚合的Converter

自定义Converter必须返回目标OAuth 2.0 提供程序可以理解的OAuth 2.0 访问令牌请求的有效RequestEntity表示。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要使用自定义配置的RestOperations 提供DefaultPasswordTokenResponseClient.setRestOperations()。默认的RestOperations 配置如下:

  • Java

  • Kotlin

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

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

需要Spring MVC FormHttpMessageConverter,因为它用于发送OAuth 2.0 访问令牌请求。

OAuth2AccessTokenResponseHttpMessageConverter 是 OAuth 2.0 访问令牌响应的HttpMessageConverter。您可以使用自定义的Converter<Map<String, String>, OAuth2AccessTokenResponse> 提供OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter(),该转换器用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,可以处理OAuth 2.0 错误,例如400 Bad Request。它使用OAuth2ErrorHttpMessageConverter将OAuth 2.0 错误参数转换为OAuth2Error

无论您自定义DefaultPasswordTokenResponseClient 还是提供您自己的OAuth2AccessTokenResponseClient 实现,都需要按如下方式配置:

  • Java

  • Kotlin

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

OAuth2AuthorizedClientProviderBuilder.builder().password() 配置一个PasswordOAuth2AuthorizedClientProvider,它是资源所有者密码凭据授权的OAuth2AuthorizedClientProvider 的实现。

使用访问令牌

考虑 OAuth 2.0 客户端注册的以下 Spring Boot 属性:

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

  • Kotlin

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

有了前面的属性和bean,您可以按如下方式获取OAuth2AccessToken

  • Java

  • Kotlin

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

HttpServletRequestHttpServletResponse 都是可选属性。如果未提供,它们默认为使用RequestContextHolder.getRequestAttributes()ServletRequestAttributes

JWT Bearer

有关 OAuth 2.0 客户端身份验证和授权授予的JWT Bearer 的更多详细信息,请参阅 JSON Web 令牌 (JWT) 配置文件。

请求访问令牌

JWT Bearer 授权的OAuth2AccessTokenResponseClient 的默认实现是DefaultJwtBearerTokenResponseClient,它在向授权服务器的令牌端点请求访问令牌时使用RestOperations

DefaultJwtBearerTokenResponseClient 非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。

自定义访问令牌请求

如果您需要自定义令牌请求的预处理,您可以使用自定义的Converter<JwtBearerGrantRequest, RequestEntity<?>> 提供DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()。默认实现JwtBearerGrantRequestEntityConverter 会构建OAuth 2.0 访问令牌请求RequestEntity 表示。但是,提供自定义的Converter 可以让您扩展令牌请求并添加自定义参数。

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

如果您只想添加其他参数,您可以使用自定义的Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> 提供JwtBearerGrantRequestEntityConverter.addParametersConverter(),它会构造一个聚合的Converter

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要使用自定义配置的RestOperations 提供DefaultJwtBearerTokenResponseClient.setRestOperations()。默认的RestOperations 配置如下:

  • Java

  • Kotlin

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

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

Spring MVC 的FormHttpMessageConverter 是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。

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

OAuth2ErrorResponseErrorHandler 是一个可以处理 OAuth 2.0 错误(例如,400 错误请求)的ResponseErrorHandler。它使用OAuth2ErrorHttpMessageConverter 将 OAuth 2.0 错误参数转换为OAuth2Error

无论您自定义DefaultJwtBearerTokenResponseClient 还是提供您自己的OAuth2AccessTokenResponseClient 实现,都需要按以下示例所示进行配置:

  • Java

  • Kotlin

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

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...

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

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

使用访问令牌

给定 OAuth 2.0 客户端注册的以下 Spring Boot 属性:

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

  • Kotlin

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

  • Kotlin

@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();

		...

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

        ...

    }
}
JwtBearerOAuth2AuthorizedClientProvider 默认情况下通过OAuth2AuthorizationContext.getPrincipal().getPrincipal() 解析Jwt 断言,因此在前面的示例中使用了JwtAuthenticationToken
如果您需要从其他来源解析Jwt 断言,您可以使用自定义的Function<OAuth2AuthorizationContext, Jwt> 提供JwtBearerOAuth2AuthorizedClientProvider.setJwtAssertionResolver()

令牌交换

有关令牌交换授权的更多详细信息,请参阅 OAuth 2.0 令牌交换。

请求访问令牌

令牌交换授权的OAuth2AccessTokenResponseClient 的默认实现是DefaultTokenExchangeTokenResponseClient,它在向授权服务器的令牌端点请求访问令牌时使用RestOperations

DefaultTokenExchangeTokenResponseClient 非常灵活,因为它允许您自定义令牌请求的预处理和/或令牌响应的后处理。

自定义访问令牌请求

如果您需要自定义令牌请求的预处理,您可以使用自定义的Converter<TokenExchangeGrantRequest, RequestEntity<?>> 提供DefaultTokenExchangeTokenResponseClient.setRequestEntityConverter()。默认实现TokenExchangeGrantRequestEntityConverter 会构建OAuth 2.0 访问令牌请求RequestEntity 表示。但是,提供自定义的Converter 可以让您扩展令牌请求并添加自定义参数。

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

如果您只想添加其他参数,您可以使用自定义的Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> 提供TokenExchangeGrantRequestEntityConverter.addParametersConverter(),它会构造一个聚合的Converter

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要使用自定义配置的RestOperations 提供DefaultTokenExchangeTokenResponseClient.setRestOperations()。默认的RestOperations 配置如下:

  • Java

  • Kotlin

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

restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
val restTemplate = RestTemplate(listOf(
        FormHttpMessageConverter(),
        OAuth2AccessTokenResponseHttpMessageConverter()))

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

Spring MVC 的FormHttpMessageConverter 是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。

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

OAuth2ErrorResponseErrorHandler 是一个可以处理 OAuth 2.0 错误(例如,400 错误请求)的ResponseErrorHandler。它使用OAuth2ErrorHttpMessageConverter 将 OAuth 2.0 错误参数转换为OAuth2Error

无论您自定义DefaultTokenExchangeTokenResponseClient 还是提供您自己的OAuth2AccessTokenResponseClient 实现,都需要按以下示例所示进行配置:

  • Java

  • Kotlin

// Customize
OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeTokenResponseClient = ...

TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider = new TokenExchangeOAuth2AuthorizedClientProvider();
tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient);

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Customize
val tokenExchangeTokenResponseClient: OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> = ...

val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient)

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

...

authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

使用访问令牌

给定 OAuth 2.0 客户端注册的以下 Spring Boot 属性:

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:token-exchange
            scope: read
        provider:
          okta:
            token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token

…以及OAuth2AuthorizedClientManager@Bean

  • Java

  • Kotlin

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

	TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
			new TokenExchangeOAuth2AuthorizedClientProvider();

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

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

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

您可以按如下方式获取OAuth2AccessToken

  • Java

  • Kotlin

@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();

		...

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

        ...

    }
}
TokenExchangeOAuth2AuthorizedClientProvider 默认情况下通过OAuth2AuthorizationContext.getPrincipal().getPrincipal() 解析主题令牌(作为OAuth2Token),因此在前面的示例中使用了JwtAuthenticationToken。默认情况下不会解析参与者令牌。
如果您需要从其他来源解析主题令牌,您可以使用自定义的Function<OAuth2AuthorizationContext, OAuth2Token> 提供TokenExchangeOAuth2AuthorizedClientProvider.setSubjectTokenResolver()
如果您需要解析参与者令牌,您可以使用自定义的Function<OAuth2AuthorizationContext, OAuth2Token> 提供TokenExchangeOAuth2AuthorizedClientProvider.setActorTokenResolver()