授权授予支持

本节介绍 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 启动授权请求重定向,并最终启动授权码授予流程。

AuthorizationCodeOAuth2AuthorizedClientProviderOAuth2AuthorizedClientProvider 的实现,用于授权码授予,它也通过 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 设置为 none (ClientAuthenticationMethod.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}

使用 URI 模板变量配置 redirect-uri 在 OAuth 2.0 客户端运行在 代理服务器 后面时特别有用。这样做可以确保在扩展 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,该 Consumer<OAuth2AuthorizationRequest.Builder> 通过包含请求参数 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 必须返回一个有效的 RequestEntity,它表示 OAuth 2.0 访问令牌请求,并且目标 OAuth 2.0 提供者可以理解。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要向 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 很灵活,因为它允许您自定义令牌请求的预处理或令牌响应的后处理。

自定义访问令牌请求

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

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

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

自定义的 Converter 必须返回一个有效的 RequestEntity,它表示 OAuth 2.0 访问令牌请求,并且目标 OAuth 2.0 提供者可以理解。

自定义访问令牌响应

另一方面,如果您需要自定义 Token 响应的后处理,则需要为 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 必须返回一个有效的 RequestEntity,它表示 OAuth 2.0 访问令牌请求,并且目标 OAuth 2.0 提供者可以理解。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,您需要提供 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 很灵活,因为它允许您自定义令牌请求的预处理或令牌响应的后处理。

自定义访问令牌请求

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

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

如果您希望仅添加其他参数,您可以向 OAuth2PasswordGrantRequestEntityConverter.addParametersConverter() 提供一个自定义的 Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>,它会构建一个聚合 Converter

自定义的 Converter 必须返回一个有效的 RequestEntity,它表示 OAuth 2.0 访问令牌请求,并且目标 OAuth 2.0 提供者可以理解。

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,您需要向 DefaultPasswordTokenResponseClient.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.setTokenResponseConverter() 提供一个自定义的 Converter<Map<String, String>, OAuth2AccessTokenResponse>,用于将 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

有关JWT Bearer授权模式的更多详细信息,请参阅JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants。

请求访问令牌

有关JWT Bearer授权模式的访问令牌请求/响应协议流程,请参阅。

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

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

自定义访问令牌请求

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

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

如果您希望仅添加其他参数,可以向JwtBearerGrantRequestEntityConverter.addParametersConverter()提供一个自定义的Converter<JwtBearerGrantRequest, MultiValueMap<String, String>>,它将构建一个聚合的Converter

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,则需要使用自定义配置的 RestOperationsDefaultJwtBearerTokenResponseClient.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 是一个 ResponseErrorHandler,它可以处理 OAuth 2.0 错误,例如 400 错误请求。它使用 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

自定义访问令牌响应

另一方面,如果您需要自定义令牌响应的后处理,您将需要使用自定义配置的RestOperationsDefaultTokenExchangeTokenResponseClient.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 是一个 ResponseErrorHandler,它可以处理 OAuth 2.0 错误,例如 400 错误请求。它使用 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()提供值。