此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.1spring-doc.cadn.net.cn

授权授予支持

本节描述了 Spring Security 对授权授予的支持。spring-doc.cadn.net.cn

授权码

请参阅 OAuth 2.0 授权框架 以了解有关授权代码授予的更多详细信息。spring-doc.cadn.net.cn

获取授权

有关授权码授予,请参阅授权请求/响应协议流程。spring-doc.cadn.net.cn

发起授权请求

OAuth2AuthorizationRequestRedirectFilter使用OAuth2AuthorizationRequestResolver要解析OAuth2AuthorizationRequest并通过将最终用户的用户代理重定向到授权服务器的授权端点来启动授权代码授予流程。spring-doc.cadn.net.cn

主要角色OAuth2AuthorizationRequestResolver是解析OAuth2AuthorizationRequest从提供的 Web 请求。 默认实现DefaultOAuth2AuthorizationRequestResolver(默认)路径上的 matches/oauth2/authorization/{registrationId},提取registrationId,并使用它来构建OAuth2AuthorizationRequest对于关联的ClientRegistration.spring-doc.cadn.net.cn

对于 OAuth 2.0 客户端注册,请考虑以下 Spring Boot 属性:spring-doc.cadn.net.cn

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

给定上述属性,具有 base path 的请求/oauth2/authorization/okta通过OAuth2AuthorizationRequestRedirectFilter并最终启动 Authorization Code 授予流程。spring-doc.cadn.net.cn

AuthorizationCodeOAuth2AuthorizedClientProviderOAuth2AuthorizedClientProvider对于 Authorization Code 授予, 它还通过OAuth2AuthorizationRequestRedirectFilter.spring-doc.cadn.net.cn

如果 OAuth 2.0 客户端是公共客户端,请按如下方式配置 OAuth 2.0 客户端注册:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

  1. client-secret被省略(或为空)spring-doc.cadn.net.cn

  2. client-authentication-method设置为none (ClientAuthenticationMethod.NONE)spring-doc.cadn.net.cn

如果 OAuth 2.0 提供者支持机密客户端的 PKCE,您可以(可选)使用DefaultOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()).spring-doc.cadn.net.cn

DefaultOAuth2AuthorizationRequestResolver还支持URItemplate 变量的redirect-uri通过使用UriComponentsBuilder.spring-doc.cadn.net.cn

以下配置使用所有支持的URI模板变量:spring-doc.cadn.net.cn

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

{baseUrl}resolve为{baseScheme}://{baseHost}{basePort}{basePath}spring-doc.cadn.net.cn

配置redirect-uriURI当 OAuth 2.0 客户端在 Proxy Server 后面运行时,模板变量特别有用。 这样做可以确保X-Forwarded-*扩展redirect-uri.spring-doc.cadn.net.cn

自定义授权请求

主要用例之一OAuth2AuthorizationRequestResolver可以实现的是能够使用高于 OAuth 2.0 授权框架中定义的标准参数的附加参数自定义授权请求。spring-doc.cadn.net.cn

例如,OpenID Connect 为授权代码流定义了其他 OAuth 2.0 请求参数,该请求参数从 OAuth 2.0 授权框架中定义的标准参数扩展而来。 其中一个扩展参数是prompt参数。spring-doc.cadn.net.cn

promptparameter 是可选的。以空格分隔、区分大小写的 ASCII 字符串值列表,用于指定 Authorization Server 是否提示最终用户重新进行身份验证和同意。定义的值为:none,login,consentselect_account.spring-doc.cadn.net.cn

以下示例显示如何配置DefaultOAuth2AuthorizationRequestResolver替换为Consumer<OAuth2AuthorizationRequest.Builder>自定义oauth2Login(),通过包含 request 参数prompt=consent.spring-doc.cadn.net.cn

@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财产。spring-doc.cadn.net.cn

例如,如果 request 参数prompt总是consent对于提供商okta,您可以按如下方式对其进行配置:spring-doc.cadn.net.cn

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

前面的示例显示了在标准参数之上添加自定义参数的常见使用案例。 或者,如果您的要求更高级,则可以通过覆盖OAuth2AuthorizationRequest.authorizationRequestUri财产。spring-doc.cadn.net.cn

OAuth2AuthorizationRequest.Builder.build()构造OAuth2AuthorizationRequest.authorizationRequestUri,它表示授权请求 URI,包括使用application/x-www-form-urlencoded格式。spring-doc.cadn.net.cn

以下示例显示了authorizationRequestCustomizer(),而是覆盖OAuth2AuthorizationRequest.authorizationRequestUri财产:spring-doc.cadn.net.cn

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从发起授权请求到收到授权响应(回调)的时间。spring-doc.cadn.net.cn

OAuth2AuthorizationRequest用于关联和验证授权响应。spring-doc.cadn.net.cn

的默认实现AuthorizationRequestRepositoryHttpSessionOAuth2AuthorizationRequestRepository,它将OAuth2AuthorizationRequestHttpSession.spring-doc.cadn.net.cn

如果您有AuthorizationRequestRepository,您可以按如下方式对其进行配置:spring-doc.cadn.net.cn

AuthorizationRequestRepository 配置
@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())
                    // ...
                )
            );
			return http.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>

申请 Access Token

有关授权码授予,请参阅访问令牌请求/响应协议流程。spring-doc.cadn.net.cn

有两种 implementation ofOAuth2AccessTokenResponseClient可用于向令牌端点发出 HTTP 请求,以获取授权码授予的访问令牌:spring-doc.cadn.net.cn

默认实现使用RestOperations实例,以在 Authorization Server 的令牌端点上交换访问令牌的授权代码。 Spring Security 6.4 引入了一个基于RestClient,它提供了类似的功能,但与组件的 Reactive 版本(基于WebClient),以便为任一堆栈上的应用程序提供一致的配置。spring-doc.cadn.net.cn

本节重点介绍RestClientAuthorizationCodeTokenResponseClient. 您可以阅读有关DefaultAuthorizationCodeTokenResponseClient在 Spring Security 6.3 文档中。spring-doc.cadn.net.cn

要选择使用RestClientAuthorizationCodeTokenResponseClient,只需提供一个 bean,如下例所示,它将被默认选取OAuth2AuthorizedClientManager自然而然:spring-doc.cadn.net.cn

Access Token 响应配置
@Bean
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
	return new RestClientAuthorizationCodeTokenResponseClient();
}
@Bean
fun accessTokenResponseClient(): OAuth2AccessTokenResponseClient<Authorization Code> {
	return RestClientAuthorizationCodeTokenResponseClient()
}

新实现将是 Spring Security 7 中的默认值。spring-doc.cadn.net.cn

RestClientAuthorizationCodeTokenResponseClient非常灵活,并提供了多个选项来自定义授权码授予的 OAuth 2.0 访问令牌请求和响应。 从以下使用案例中进行选择以了解更多信息:spring-doc.cadn.net.cn

自定义 Access Token 请求

RestClientAuthorizationCodeTokenResponseClient提供自定义 OAuth 2.0 Access Token Request 的 HTTP 头和请求参数的 hook。spring-doc.cadn.net.cn

自定义请求标头

自定义 HTTP 标头有两个选项:spring-doc.cadn.net.cn

您可以包含其他标头,而不会影响使用addHeadersConverter(). 以下示例添加了一个User-Agent标头添加到请求中时,registrationIdspring:spring-doc.cadn.net.cn

包括其他 HTTP 标头
RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
	new RestClientAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.addHeadersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	HttpHeaders headers = new HttpHeaders();
	if (clientRegistration.getRegistrationId().equals("spring")) {
		headers.set(HttpHeaders.USER_AGENT, "my-user-agent");
	}
	return headers;
});
val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
accessTokenResponseClient.addHeadersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val headers = HttpHeaders()
	if (clientRegistration.getRegistrationId() == "spring") {
        headers[HttpHeaders.USER_AGENT] = "my-user-agent"
	}
	headers
}

您可以通过重复使用来完全自定义标头DefaultOAuth2TokenRequestHeadersConverter或使用setHeadersConverter(). 以下示例重用DefaultOAuth2TokenRequestHeadersConverter并禁用encodeClientCredentials,以便 HTTP Basic 凭证不再使用application/x-www-form-urlencoded:spring-doc.cadn.net.cn

自定义 HTTP 标头
DefaultOAuth2TokenRequestHeadersConverter headersConverter =
	new DefaultOAuth2TokenRequestHeadersConverter();
headersConverter.setEncodeClientCredentials(false);

RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
	new RestClientAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.setHeadersConverter(headersConverter);
val headersConverter = DefaultOAuth2TokenRequestHeadersConverter()
headersConverter.setEncodeClientCredentials(false)

val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
accessTokenResponseClient.setHeadersConverter(headersConverter)

自定义请求参数

有三个选项可用于自定义请求参数:spring-doc.cadn.net.cn

setParametersConverter()不完全自定义参数,因为它需要用户自己提供所有默认参数。 默认参数始终提供,但可以通过调用setParametersCustomizer().spring-doc.cadn.net.cn

您可以包含其他参数,而不会影响使用addParametersConverter(). 以下示例添加了一个audience参数添加到请求中时,registrationIdkeycloak:spring-doc.cadn.net.cn

包括其他请求参数
RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
	new RestClientAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.addParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
	if (clientRegistration.getRegistrationId().equals("keycloak")) {
		parameters.set(OAuth2ParameterNames.AUDIENCE, "my-audience");
	}
	return parameters;
});
val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
accessTokenResponseClient.addParametersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "keycloak") {
        parameters[OAuth2ParameterNames.AUDIENCE] = "my-audience"
	}
	parameters
}

您可以使用setParametersConverter(). 以下示例将client_id参数,当registrationIdokta:spring-doc.cadn.net.cn

覆盖请求参数
RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
	new RestClientAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.setParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
	if (clientRegistration.getRegistrationId().equals("okta")) {
		parameters.set(OAuth2ParameterNames.CLIENT_ID, "my-client");
	}
	return parameters;
});
val parametersConverter = DefaultOAuth2TokenRequestParametersConverter<OAuth2AuthorizationCodeGrantRequest>()
parametersConverter.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
accessTokenResponseClient.setParametersConverter { grantRequest ->
    val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "okta") {
        parameters[OAuth2ParameterNames.CLIENT_ID] = "my-client"
	}
	parameters
}

您可以使用setParametersCustomizer(). 以下示例省略了client_id参数,当client_assertion参数:spring-doc.cadn.net.cn

省略请求参数
RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
	new RestClientAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.setParametersCustomizer(parameters -> {
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID);
	}
});
val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
accessTokenResponseClient.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

自定义访问令牌响应

RestClientAuthorizationCodeTokenResponseClient提供用于自定义响应参数和 OAuth 2.0 Access Token 响应错误处理的钩子。spring-doc.cadn.net.cn

自定义WebClient

您可以通过提供预配置的RestClientsetRestClient(). 默认的RestClient配置如下:spring-doc.cadn.net.cn

违约RestClient配置
RestClient restClient = RestClient.builder()
	.messageConverters(messageConverters -> {
		messageConverters.clear();
		messageConverters.add(new FormHttpMessageConverter());
		messageConverters.add(new OAuth2AccessTokenResponseHttpMessageConverter());
	})
	.defaultStatusHandler(new OAuth2ErrorResponseErrorHandler())
	.build();

RestClientAuthorizationCodeTokenResponseClient accessTokenResponseClient =
	new RestClientAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.setRestClient(restClient);
val restClient = RestClient.builder()
	.messageConverters { messageConverters ->
		messageConverters.clear()
		messageConverters.add(FormHttpMessageConverter())
		messageConverters.add(OAuth2AccessTokenResponseHttpMessageConverter())
	}
	.defaultStatusHandler(OAuth2ErrorResponseErrorHandler())
	.build()

val accessTokenResponseClient = RestClientAuthorizationCodeTokenResponseClient()
accessTokenResponseClient.setRestClient(restClient)

OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。 您可以自定义 Token Response 参数到OAuth2AccessTokenResponse通过调用setAccessTokenResponseConverter(). 默认实现为DefaultMapOAuth2AccessTokenResponseConverter.spring-doc.cadn.net.cn

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如400 Bad Request. 它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error. 您可以自定义 Token Response 参数到OAuth2Error通过调用setErrorConverter().spring-doc.cadn.net.cn

Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。spring-doc.cadn.net.cn

自定义响应参数

以下示例提供了自定义 Token Response 参数转换为OAuth2AccessTokenResponse:spring-doc.cadn.net.cn

自定义 Access Token Response Converter
OAuth2AccessTokenResponseHttpMessageConverter accessTokenResponseMessageConverter =
	new OAuth2AccessTokenResponseHttpMessageConverter();
accessTokenResponseMessageConverter.setAccessTokenResponseConverter(parameters -> {
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build();
});
val accessTokenResponseMessageConverter = OAuth2AccessTokenResponseHttpMessageConverter()
accessTokenResponseMessageConverter.setAccessTokenResponseConverter { parameters ->
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build()
}

自定义错误处理

以下示例提供了自定义 Error 参数到OAuth2Error:spring-doc.cadn.net.cn

自定义 Access Token 错误处理程序
OAuth2ErrorHttpMessageConverter errorConverter =
	new OAuth2ErrorHttpMessageConverter();
errorConverter.setErrorConverter(parameters -> {
	// ...
	return new OAuth2Error("custom-error", "custom description", "custom-uri");
});

OAuth2ErrorResponseErrorHandler errorHandler =
	new OAuth2ErrorResponseErrorHandler();
errorHandler.setErrorConverter(errorConverter);
val errorConverter = OAuth2ErrorHttpMessageConverter()
errorConverter.setErrorConverter { parameters ->
	// ...
	return OAuth2Error("custom-error", "custom description", "custom-uri")
}

val errorHandler = OAuth2ErrorResponseErrorHandler()
errorHandler.setErrorConverter(errorConverter)

使用 DSL 进行自定义

无论您是否自定义RestClientAuthorizationCodeTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,你可以使用 DSL 配置它(作为发布 bean 的替代方法),如下所示:spring-doc.cadn.net.cn

通过 DSL 配置 Access Token 响应
@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 授权框架 以了解有关刷新令牌的更多详细信息。spring-doc.cadn.net.cn

刷新 Access Token

请参阅 访问令牌请求/响应协议流程 以了解刷新令牌授予。spring-doc.cadn.net.cn

有两种 implementation ofOAuth2AccessTokenResponseClient,可用于向令牌端点发出 HTTP 请求,以获取刷新令牌授予的访问令牌:spring-doc.cadn.net.cn

默认实现使用RestOperations实例,以在 Authorization Server 的令牌端点上交换访问令牌的授权代码。 Spring Security 6.4 引入了一个基于RestClient,它提供了类似的功能,但与组件的 Reactive 版本(基于WebClient),以便为任一堆栈上的应用程序提供一致的配置。spring-doc.cadn.net.cn

本节重点介绍RestClientRefreshTokenTokenResponseClient. 您可以阅读有关DefaultRefreshTokenTokenResponseClient在 Spring Security 6.3 文档中。spring-doc.cadn.net.cn

要选择使用RestClientRefreshTokenTokenResponseClient,只需提供一个 bean,如下例所示,它将被默认选取OAuth2AuthorizedClientManager自然而然:spring-doc.cadn.net.cn

Access Token 响应配置
@Bean
public OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient() {
	return new RestClientRefreshTokenTokenResponseClient();
}
@Bean
fun accessTokenResponseClient(): OAuth2AccessTokenResponseClient<Refresh Token> {
	return RestClientRefreshTokenTokenResponseClient()
}

新实现将是 Spring Security 7 中的默认值。spring-doc.cadn.net.cn

RestClientRefreshTokenTokenResponseClient非常灵活,并提供了多个选项来自定义 OAuth 2.0 访问令牌请求和刷新令牌授予的响应。 从以下使用案例中进行选择以了解更多信息:spring-doc.cadn.net.cn

自定义 Access Token 请求

RestClientRefreshTokenTokenResponseClient提供自定义 OAuth 2.0 Access Token Request 的 HTTP 头和请求参数的 hook。spring-doc.cadn.net.cn

自定义请求标头

自定义 HTTP 标头有两个选项:spring-doc.cadn.net.cn

您可以包含其他标头,而不会影响使用addHeadersConverter(). 以下示例添加了一个User-Agent标头添加到请求中时,registrationIdspring:spring-doc.cadn.net.cn

包括其他 HTTP 标头
RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
	new RestClientRefreshTokenTokenResponseClient();
accessTokenResponseClient.addHeadersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	HttpHeaders headers = new HttpHeaders();
	if (clientRegistration.getRegistrationId().equals("spring")) {
		headers.set(HttpHeaders.USER_AGENT, "my-user-agent");
	}
	return headers;
});
val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
accessTokenResponseClient.addHeadersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val headers = HttpHeaders()
	if (clientRegistration.getRegistrationId() == "spring") {
        headers[HttpHeaders.USER_AGENT] = "my-user-agent"
	}
	headers
}

您可以通过重复使用来完全自定义标头DefaultOAuth2TokenRequestHeadersConverter或使用setHeadersConverter(). 以下示例重用DefaultOAuth2TokenRequestHeadersConverter并禁用encodeClientCredentials,以便 HTTP Basic 凭证不再使用application/x-www-form-urlencoded:spring-doc.cadn.net.cn

自定义 HTTP 标头
DefaultOAuth2TokenRequestHeadersConverter headersConverter =
	new DefaultOAuth2TokenRequestHeadersConverter();
headersConverter.setEncodeClientCredentials(false);

RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
	new RestClientRefreshTokenTokenResponseClient();
accessTokenResponseClient.setHeadersConverter(headersConverter);
val headersConverter = DefaultOAuth2TokenRequestHeadersConverter()
headersConverter.setEncodeClientCredentials(false)

val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
accessTokenResponseClient.setHeadersConverter(headersConverter)

自定义请求参数

有三个选项可用于自定义请求参数:spring-doc.cadn.net.cn

setParametersConverter()不完全自定义参数,因为它需要用户自己提供所有默认参数。 默认参数始终提供,但可以通过调用setParametersCustomizer().spring-doc.cadn.net.cn

您可以包含其他参数,而不会影响使用addParametersConverter(). 以下示例添加了一个audience参数添加到请求中时,registrationIdkeycloak:spring-doc.cadn.net.cn

包括其他请求参数
RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
	new RestClientRefreshTokenTokenResponseClient();
accessTokenResponseClient.addParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
	if (clientRegistration.getRegistrationId().equals("keycloak")) {
		parameters.set(OAuth2ParameterNames.AUDIENCE, "my-audience");
	}
	return parameters;
});
val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
accessTokenResponseClient.addParametersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "keycloak") {
        parameters[OAuth2ParameterNames.AUDIENCE] = "my-audience"
	}
	parameters
}

您可以使用setParametersConverter(). 以下示例将client_id参数,当registrationIdokta:spring-doc.cadn.net.cn

覆盖请求参数
RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
	new RestClientRefreshTokenTokenResponseClient();
accessTokenResponseClient.setParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
	if (clientRegistration.getRegistrationId().equals("okta")) {
		parameters.set(OAuth2ParameterNames.CLIENT_ID, "my-client");
	}
	return parameters;
});
val parametersConverter = DefaultOAuth2TokenRequestParametersConverter<OAuth2RefreshTokenGrantRequest>()
parametersConverter.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
accessTokenResponseClient.setParametersConverter { grantRequest ->
    val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "okta") {
        parameters[OAuth2ParameterNames.CLIENT_ID] = "my-client"
	}
	parameters
}

您可以使用setParametersCustomizer(). 以下示例省略了client_id参数,当client_assertion参数:spring-doc.cadn.net.cn

省略请求参数
RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
	new RestClientRefreshTokenTokenResponseClient();
accessTokenResponseClient.setParametersCustomizer(parameters -> {
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID);
	}
});
val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
accessTokenResponseClient.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

自定义访问令牌响应

RestClientRefreshTokenTokenResponseClient提供用于自定义响应参数和 OAuth 2.0 Access Token 响应错误处理的钩子。spring-doc.cadn.net.cn

自定义WebClient

您可以通过提供预配置的RestClientsetRestClient(). 默认的RestClient配置如下:spring-doc.cadn.net.cn

违约RestClient配置
RestClient restClient = RestClient.builder()
	.messageConverters(messageConverters -> {
		messageConverters.clear();
		messageConverters.add(new FormHttpMessageConverter());
		messageConverters.add(new OAuth2AccessTokenResponseHttpMessageConverter());
	})
	.defaultStatusHandler(new OAuth2ErrorResponseErrorHandler())
	.build();

RestClientRefreshTokenTokenResponseClient accessTokenResponseClient =
	new RestClientRefreshTokenTokenResponseClient();
accessTokenResponseClient.setRestClient(restClient);
val restClient = RestClient.builder()
	.messageConverters { messageConverters ->
		messageConverters.clear()
		messageConverters.add(FormHttpMessageConverter())
		messageConverters.add(OAuth2AccessTokenResponseHttpMessageConverter())
	}
	.defaultStatusHandler(OAuth2ErrorResponseErrorHandler())
	.build()

val accessTokenResponseClient = RestClientRefreshTokenTokenResponseClient()
accessTokenResponseClient.setRestClient(restClient)

OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。 您可以自定义 Token Response 参数到OAuth2AccessTokenResponse通过调用setAccessTokenResponseConverter(). 默认实现为DefaultMapOAuth2AccessTokenResponseConverter.spring-doc.cadn.net.cn

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如400 Bad Request. 它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error. 您可以自定义 Token Response 参数到OAuth2Error通过调用setErrorConverter().spring-doc.cadn.net.cn

Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。spring-doc.cadn.net.cn

自定义响应参数

以下示例提供了自定义 Token Response 参数转换为OAuth2AccessTokenResponse:spring-doc.cadn.net.cn

自定义 Access Token Response Converter
OAuth2AccessTokenResponseHttpMessageConverter accessTokenResponseMessageConverter =
	new OAuth2AccessTokenResponseHttpMessageConverter();
accessTokenResponseMessageConverter.setAccessTokenResponseConverter(parameters -> {
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build();
});
val accessTokenResponseMessageConverter = OAuth2AccessTokenResponseHttpMessageConverter()
accessTokenResponseMessageConverter.setAccessTokenResponseConverter { parameters ->
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build()
}

自定义错误处理

以下示例提供了自定义 Error 参数到OAuth2Error:spring-doc.cadn.net.cn

自定义 Access Token 错误处理程序
OAuth2ErrorHttpMessageConverter errorConverter =
	new OAuth2ErrorHttpMessageConverter();
errorConverter.setErrorConverter(parameters -> {
	// ...
	return new OAuth2Error("custom-error", "custom description", "custom-uri");
});

OAuth2ErrorResponseErrorHandler errorHandler =
	new OAuth2ErrorResponseErrorHandler();
errorHandler.setErrorConverter(errorConverter);
val errorConverter = OAuth2ErrorHttpMessageConverter()
errorConverter.setErrorConverter { parameters ->
	// ...
	return OAuth2Error("custom-error", "custom description", "custom-uri")
}

val errorHandler = OAuth2ErrorResponseErrorHandler()
errorHandler.setErrorConverter(errorConverter)

使用 Builder 进行自定义

无论您是否自定义RestClientRefreshTokenTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您可以使用OAuth2AuthorizedClientProviderBuilder(作为发布 bean 的替代方法),如下所示:spring-doc.cadn.net.cn

通过 Builder 配置 Access Token 响应
// 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对于 Refresh Token 授权。spring-doc.cadn.net.cn

OAuth2RefreshToken可以选择在 Access Token Response 中返回authorization_codepassword授权类型。 如果OAuth2AuthorizedClient.getRefreshToken()可用,并且OAuth2AuthorizedClient.getAccessToken()已过期,则由RefreshTokenOAuth2AuthorizedClientProvider.spring-doc.cadn.net.cn

客户端凭证

请参阅 OAuth 2.0 授权框架,了解有关客户端凭证授予的更多详细信息。spring-doc.cadn.net.cn

申请 Access Token

请参阅访问令牌请求/响应协议流程,了解客户端凭证授予。spring-doc.cadn.net.cn

有两种 implementation ofOAuth2AccessTokenResponseClient可用于向令牌端点发出 HTTP 请求,以获取客户端凭证授予的访问令牌:spring-doc.cadn.net.cn

默认实现使用RestOperations实例,以在 Authorization Server 的令牌端点上交换访问令牌的授权代码。 Spring Security 6.4 引入了一个基于RestClient,它提供了类似的功能,但与组件的 Reactive 版本(基于WebClient),以便为任一堆栈上的应用程序提供一致的配置。spring-doc.cadn.net.cn

本节重点介绍RestClientClientCredentialsTokenResponseClient. 您可以阅读有关DefaultClientCredentialsTokenResponseClient在 Spring Security 6.3 文档中。spring-doc.cadn.net.cn

要选择使用RestClientClientCredentialsTokenResponseClient,只需提供一个 bean,如下例所示,它将被默认选取OAuth2AuthorizedClientManager自然而然:spring-doc.cadn.net.cn

Access Token 响应配置
@Bean
public OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient() {
	return new RestClientClientCredentialsTokenResponseClient();
}
@Bean
fun accessTokenResponseClient(): OAuth2AccessTokenResponseClient<Client Credentials> {
	return RestClientClientCredentialsTokenResponseClient()
}

新实现将是 Spring Security 7 中的默认值。spring-doc.cadn.net.cn

RestClientClientCredentialsTokenResponseClient非常灵活,并提供了多个选项来自定义客户端凭证授予的 OAuth 2.0 访问令牌请求和响应。 从以下使用案例中进行选择以了解更多信息:spring-doc.cadn.net.cn

自定义 Access Token 请求

RestClientClientCredentialsTokenResponseClient提供自定义 OAuth 2.0 Access Token Request 的 HTTP 头和请求参数的 hook。spring-doc.cadn.net.cn

自定义请求标头

自定义 HTTP 标头有两个选项:spring-doc.cadn.net.cn

您可以包含其他标头,而不会影响使用addHeadersConverter(). 以下示例添加了一个User-Agent标头添加到请求中时,registrationIdspring:spring-doc.cadn.net.cn

包括其他 HTTP 标头
RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
	new RestClientClientCredentialsTokenResponseClient();
accessTokenResponseClient.addHeadersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	HttpHeaders headers = new HttpHeaders();
	if (clientRegistration.getRegistrationId().equals("spring")) {
		headers.set(HttpHeaders.USER_AGENT, "my-user-agent");
	}
	return headers;
});
val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
accessTokenResponseClient.addHeadersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val headers = HttpHeaders()
	if (clientRegistration.getRegistrationId() == "spring") {
        headers[HttpHeaders.USER_AGENT] = "my-user-agent"
	}
	headers
}

您可以通过重复使用来完全自定义标头DefaultOAuth2TokenRequestHeadersConverter或使用setHeadersConverter(). 以下示例重用DefaultOAuth2TokenRequestHeadersConverter并禁用encodeClientCredentials,以便 HTTP Basic 凭证不再使用application/x-www-form-urlencoded:spring-doc.cadn.net.cn

自定义 HTTP 标头
DefaultOAuth2TokenRequestHeadersConverter headersConverter =
	new DefaultOAuth2TokenRequestHeadersConverter();
headersConverter.setEncodeClientCredentials(false);

RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
	new RestClientClientCredentialsTokenResponseClient();
accessTokenResponseClient.setHeadersConverter(headersConverter);
val headersConverter = DefaultOAuth2TokenRequestHeadersConverter()
headersConverter.setEncodeClientCredentials(false)

val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
accessTokenResponseClient.setHeadersConverter(headersConverter)

自定义请求参数

有三个选项可用于自定义请求参数:spring-doc.cadn.net.cn

setParametersConverter()不完全自定义参数,因为它需要用户自己提供所有默认参数。 默认参数始终提供,但可以通过调用setParametersCustomizer().spring-doc.cadn.net.cn

您可以包含其他参数,而不会影响使用addParametersConverter(). 以下示例添加了一个audience参数添加到请求中时,registrationIdkeycloak:spring-doc.cadn.net.cn

包括其他请求参数
RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
	new RestClientClientCredentialsTokenResponseClient();
accessTokenResponseClient.addParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
	if (clientRegistration.getRegistrationId().equals("keycloak")) {
		parameters.set(OAuth2ParameterNames.AUDIENCE, "my-audience");
	}
	return parameters;
});
val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
accessTokenResponseClient.addParametersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "keycloak") {
        parameters[OAuth2ParameterNames.AUDIENCE] = "my-audience"
	}
	parameters
}

您可以使用setParametersConverter(). 以下示例将client_id参数,当registrationIdokta:spring-doc.cadn.net.cn

覆盖请求参数
RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
	new RestClientClientCredentialsTokenResponseClient();
accessTokenResponseClient.setParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
	if (clientRegistration.getRegistrationId().equals("okta")) {
		parameters.set(OAuth2ParameterNames.CLIENT_ID, "my-client");
	}
	return parameters;
});
val parametersConverter = DefaultOAuth2TokenRequestParametersConverter<OAuth2ClientCredentialsGrantRequest>()
parametersConverter.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
accessTokenResponseClient.setParametersConverter { grantRequest ->
    val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "okta") {
        parameters[OAuth2ParameterNames.CLIENT_ID] = "my-client"
	}
	parameters
}

您可以使用setParametersCustomizer(). 以下示例省略了client_id参数,当client_assertion参数:spring-doc.cadn.net.cn

省略请求参数
RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
	new RestClientClientCredentialsTokenResponseClient();
accessTokenResponseClient.setParametersCustomizer(parameters -> {
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID);
	}
});
val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
accessTokenResponseClient.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

自定义访问令牌响应

RestClientClientCredentialsTokenResponseClient提供用于自定义响应参数和 OAuth 2.0 Access Token 响应错误处理的钩子。spring-doc.cadn.net.cn

自定义WebClient

您可以通过提供预配置的RestClientsetRestClient(). 默认的RestClient配置如下:spring-doc.cadn.net.cn

违约RestClient配置
RestClient restClient = RestClient.builder()
	.messageConverters(messageConverters -> {
		messageConverters.clear();
		messageConverters.add(new FormHttpMessageConverter());
		messageConverters.add(new OAuth2AccessTokenResponseHttpMessageConverter());
	})
	.defaultStatusHandler(new OAuth2ErrorResponseErrorHandler())
	.build();

RestClientClientCredentialsTokenResponseClient accessTokenResponseClient =
	new RestClientClientCredentialsTokenResponseClient();
accessTokenResponseClient.setRestClient(restClient);
val restClient = RestClient.builder()
	.messageConverters { messageConverters ->
		messageConverters.clear()
		messageConverters.add(FormHttpMessageConverter())
		messageConverters.add(OAuth2AccessTokenResponseHttpMessageConverter())
	}
	.defaultStatusHandler(OAuth2ErrorResponseErrorHandler())
	.build()

val accessTokenResponseClient = RestClientClientCredentialsTokenResponseClient()
accessTokenResponseClient.setRestClient(restClient)

OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。 您可以自定义 Token Response 参数到OAuth2AccessTokenResponse通过调用setAccessTokenResponseConverter(). 默认实现为DefaultMapOAuth2AccessTokenResponseConverter.spring-doc.cadn.net.cn

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如400 Bad Request. 它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error. 您可以自定义 Token Response 参数到OAuth2Error通过调用setErrorConverter().spring-doc.cadn.net.cn

Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。spring-doc.cadn.net.cn

自定义响应参数

以下示例提供了自定义 Token Response 参数转换为OAuth2AccessTokenResponse:spring-doc.cadn.net.cn

自定义 Access Token Response Converter
OAuth2AccessTokenResponseHttpMessageConverter accessTokenResponseMessageConverter =
	new OAuth2AccessTokenResponseHttpMessageConverter();
accessTokenResponseMessageConverter.setAccessTokenResponseConverter(parameters -> {
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build();
});
val accessTokenResponseMessageConverter = OAuth2AccessTokenResponseHttpMessageConverter()
accessTokenResponseMessageConverter.setAccessTokenResponseConverter { parameters ->
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build()
}

自定义错误处理

以下示例提供了自定义 Error 参数到OAuth2Error:spring-doc.cadn.net.cn

自定义 Access Token 错误处理程序
OAuth2ErrorHttpMessageConverter errorConverter =
	new OAuth2ErrorHttpMessageConverter();
errorConverter.setErrorConverter(parameters -> {
	// ...
	return new OAuth2Error("custom-error", "custom description", "custom-uri");
});

OAuth2ErrorResponseErrorHandler errorHandler =
	new OAuth2ErrorResponseErrorHandler();
errorHandler.setErrorConverter(errorConverter);
val errorConverter = OAuth2ErrorHttpMessageConverter()
errorConverter.setErrorConverter { parameters ->
	// ...
	return OAuth2Error("custom-error", "custom description", "custom-uri")
}

val errorHandler = OAuth2ErrorResponseErrorHandler()
errorHandler.setErrorConverter(errorConverter)

使用 Builder 进行自定义

无论您是否自定义RestClientClientCredentialsTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您可以使用OAuth2AuthorizedClientProviderBuilder(作为发布 bean 的替代方法),如下所示:spring-doc.cadn.net.cn

通过 Builder 配置 Access Token 响应
// 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的 Client Credentials grant(客户端凭证)授予。spring-doc.cadn.net.cn

使用 Access Token

对于 OAuth 2.0 客户端注册,请考虑以下 Spring Boot 属性:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

@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如下:spring-doc.cadn.net.cn

@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都是 OPTIONAL 属性。 如果未提供,则默认为ServletRequestAttributes通过使用RequestContextHolder.getRequestAttributes().spring-doc.cadn.net.cn

资源所有者密码凭证

请参阅 OAuth 2.0 授权框架 有关资源所有者密码凭证授予的更多详细信息。spring-doc.cadn.net.cn

申请 Access Token

请参阅 Access Token Request/Response 协议流程,了解 Resource Owner Password Credentials 授予。spring-doc.cadn.net.cn

的默认实现OAuth2AccessTokenResponseClient对于 Resource Owner Password Credentials,grant 为DefaultPasswordTokenResponseClient,它使用RestOperations在 Authorization Server 的令牌端点请求访问令牌时。spring-doc.cadn.net.cn

DefaultPasswordTokenResponseClient类和对 Resource Owner Password Credentials 授予的支持已弃用。 此部分将在 Spring Security 7 中删除。spring-doc.cadn.net.cn

DefaultPasswordTokenResponseClient非常灵活,因为它允许您自定义 Token Request 的预处理或 Token Response 的后处理。spring-doc.cadn.net.cn

自定义 Access Token 请求

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

要仅自定义请求的参数,您可以提供OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()使用自定义Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>以完全覆盖随请求发送的参数。这通常比构造RequestEntity径直。spring-doc.cadn.net.cn

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

自定义Converter必须返回有效的RequestEntity预期的 OAuth 2.0 提供者理解的 OAuth 2.0 访问令牌请求的表示形式。spring-doc.cadn.net.cn

自定义访问令牌响应

另一方面,如果需要自定义 Token Response 的后处理,则需要提供DefaultPasswordTokenResponseClient.setRestOperations()使用自定义配置RestOperations. 默认的RestOperations配置如下:spring-doc.cadn.net.cn

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

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

restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()

Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。spring-doc.cadn.net.cn

OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。 您可以提供OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter()使用自定义Converter<Map<String, String>, OAuth2AccessTokenResponse>用于将 OAuth 2.0 访问令牌响应参数转换为OAuth2AccessTokenResponse.spring-doc.cadn.net.cn

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如400 Bad Request. 它使用OAuth2ErrorHttpMessageConverter要将 OAuth 2.0 Error 参数转换为OAuth2Error.spring-doc.cadn.net.cn

使用 Builder 进行自定义

无论您是否自定义DefaultPasswordTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您需要按如下方式进行配置:spring-doc.cadn.net.cn

通过 Builder 配置 Access Token 响应
// 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对于 Resource Owner Password Credentials (资源所有者密码凭证) 授予。spring-doc.cadn.net.cn

使用 Access Token

对于 OAuth 2.0 客户端注册,请考虑以下 Spring Boot 属性:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

@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如下:spring-doc.cadn.net.cn

@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都是 OPTIONAL 属性。 如果未提供,则默认为ServletRequestAttributesRequestContextHolder.getRequestAttributes().spring-doc.cadn.net.cn

JWT 持有者

有关 JWT 不记名授权的更多详细信息,请参阅 OAuth 2.0 客户端身份验证和授权的 JSON Web 令牌 (JWT) 配置文件。spring-doc.cadn.net.cn

申请 Access Token

请参阅 JWT Bearer 授权的访问令牌请求/响应协议流程。spring-doc.cadn.net.cn

有两种 implementation ofOAuth2AccessTokenResponseClient可用于向令牌端点发出 HTTP 请求,以获取 JWT Bearer 授权的访问令牌:spring-doc.cadn.net.cn

默认实现使用RestOperations实例,以在 Authorization Server 的令牌端点上交换访问令牌的授权代码。 Spring Security 6.4 引入了一个基于RestClient,它提供了类似的功能,但与组件的 Reactive 版本(基于WebClient),以便为任一堆栈上的应用程序提供一致的配置。spring-doc.cadn.net.cn

本节重点介绍RestClientJwtBearerTokenResponseClient. 您可以阅读有关DefaultClientCredentialsTokenResponseClient在 Spring Security 6.3 文档中。spring-doc.cadn.net.cn

要选择使用RestClientJwtBearerTokenResponseClient,只需提供一个 bean,如下例所示,它将被默认选取OAuth2AuthorizedClientManager自然而然:spring-doc.cadn.net.cn

Access Token 响应配置
@Bean
public OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient() {
	return new RestClientJwtBearerTokenResponseClient();
}
@Bean
fun accessTokenResponseClient(): OAuth2AccessTokenResponseClient<JWT Bearer> {
	return RestClientJwtBearerTokenResponseClient()
}

新实现将是 Spring Security 7 中的默认值。spring-doc.cadn.net.cn

RestClientJwtBearerTokenResponseClient非常灵活,并提供了多个选项,用于自定义 JWT Bearer 授权的 OAuth 2.0 访问令牌请求和响应。 从以下使用案例中进行选择以了解更多信息:spring-doc.cadn.net.cn

自定义 Access Token 请求

RestClientJwtBearerTokenResponseClient提供自定义 OAuth 2.0 Access Token Request 的 HTTP 头和请求参数的 hook。spring-doc.cadn.net.cn

自定义请求标头

自定义 HTTP 标头有两个选项:spring-doc.cadn.net.cn

您可以包含其他标头,而不会影响使用addHeadersConverter(). 以下示例添加了一个User-Agent标头添加到请求中时,registrationIdspring:spring-doc.cadn.net.cn

包括其他 HTTP 标头
RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
	new RestClientJwtBearerTokenResponseClient();
accessTokenResponseClient.addHeadersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	HttpHeaders headers = new HttpHeaders();
	if (clientRegistration.getRegistrationId().equals("spring")) {
		headers.set(HttpHeaders.USER_AGENT, "my-user-agent");
	}
	return headers;
});
val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
accessTokenResponseClient.addHeadersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val headers = HttpHeaders()
	if (clientRegistration.getRegistrationId() == "spring") {
        headers[HttpHeaders.USER_AGENT] = "my-user-agent"
	}
	headers
}

您可以通过重复使用来完全自定义标头DefaultOAuth2TokenRequestHeadersConverter或使用setHeadersConverter(). 以下示例重用DefaultOAuth2TokenRequestHeadersConverter并禁用encodeClientCredentials,以便 HTTP Basic 凭证不再使用application/x-www-form-urlencoded:spring-doc.cadn.net.cn

自定义 HTTP 标头
DefaultOAuth2TokenRequestHeadersConverter headersConverter =
	new DefaultOAuth2TokenRequestHeadersConverter();
headersConverter.setEncodeClientCredentials(false);

RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
	new RestClientJwtBearerTokenResponseClient();
accessTokenResponseClient.setHeadersConverter(headersConverter);
val headersConverter = DefaultOAuth2TokenRequestHeadersConverter()
headersConverter.setEncodeClientCredentials(false)

val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
accessTokenResponseClient.setHeadersConverter(headersConverter)

自定义请求参数

有三个选项可用于自定义请求参数:spring-doc.cadn.net.cn

setParametersConverter()不完全自定义参数,因为它需要用户自己提供所有默认参数。 默认参数始终提供,但可以通过调用setParametersCustomizer().spring-doc.cadn.net.cn

您可以包含其他参数,而不会影响使用addParametersConverter(). 以下示例添加了一个audience参数添加到请求中时,registrationIdkeycloak:spring-doc.cadn.net.cn

包括其他请求参数
RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
	new RestClientJwtBearerTokenResponseClient();
accessTokenResponseClient.addParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
	if (clientRegistration.getRegistrationId().equals("keycloak")) {
		parameters.set(OAuth2ParameterNames.AUDIENCE, "my-audience");
	}
	return parameters;
});
val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
accessTokenResponseClient.addParametersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "keycloak") {
        parameters[OAuth2ParameterNames.AUDIENCE] = "my-audience"
	}
	parameters
}

您可以使用setParametersConverter(). 以下示例将client_id参数,当registrationIdokta:spring-doc.cadn.net.cn

覆盖请求参数
RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
	new RestClientJwtBearerTokenResponseClient();
accessTokenResponseClient.setParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
	if (clientRegistration.getRegistrationId().equals("okta")) {
		parameters.set(OAuth2ParameterNames.CLIENT_ID, "my-client");
	}
	return parameters;
});
val parametersConverter = DefaultOAuth2TokenRequestParametersConverter<JwtBearerGrantRequest>()
parametersConverter.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
accessTokenResponseClient.setParametersConverter { grantRequest ->
    val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "okta") {
        parameters[OAuth2ParameterNames.CLIENT_ID] = "my-client"
	}
	parameters
}

您可以使用setParametersCustomizer(). 以下示例省略了client_id参数,当client_assertion参数:spring-doc.cadn.net.cn

省略请求参数
RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
	new RestClientJwtBearerTokenResponseClient();
accessTokenResponseClient.setParametersCustomizer(parameters -> {
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID);
	}
});
val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
accessTokenResponseClient.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

自定义访问令牌响应

RestClientJwtBearerTokenResponseClient提供用于自定义响应参数和 OAuth 2.0 Access Token 响应错误处理的钩子。spring-doc.cadn.net.cn

自定义WebClient

您可以通过提供预配置的RestClientsetRestClient(). 默认的RestClient配置如下:spring-doc.cadn.net.cn

违约RestClient配置
RestClient restClient = RestClient.builder()
	.messageConverters(messageConverters -> {
		messageConverters.clear();
		messageConverters.add(new FormHttpMessageConverter());
		messageConverters.add(new OAuth2AccessTokenResponseHttpMessageConverter());
	})
	.defaultStatusHandler(new OAuth2ErrorResponseErrorHandler())
	.build();

RestClientJwtBearerTokenResponseClient accessTokenResponseClient =
	new RestClientJwtBearerTokenResponseClient();
accessTokenResponseClient.setRestClient(restClient);
val restClient = RestClient.builder()
	.messageConverters { messageConverters ->
		messageConverters.clear()
		messageConverters.add(FormHttpMessageConverter())
		messageConverters.add(OAuth2AccessTokenResponseHttpMessageConverter())
	}
	.defaultStatusHandler(OAuth2ErrorResponseErrorHandler())
	.build()

val accessTokenResponseClient = RestClientJwtBearerTokenResponseClient()
accessTokenResponseClient.setRestClient(restClient)

OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。 您可以自定义 Token Response 参数到OAuth2AccessTokenResponse通过调用setAccessTokenResponseConverter(). 默认实现为DefaultMapOAuth2AccessTokenResponseConverter.spring-doc.cadn.net.cn

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如400 Bad Request. 它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error. 您可以自定义 Token Response 参数到OAuth2Error通过调用setErrorConverter().spring-doc.cadn.net.cn

Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。spring-doc.cadn.net.cn

自定义响应参数

以下示例提供了自定义 Token Response 参数转换为OAuth2AccessTokenResponse:spring-doc.cadn.net.cn

自定义 Access Token Response Converter
OAuth2AccessTokenResponseHttpMessageConverter accessTokenResponseMessageConverter =
	new OAuth2AccessTokenResponseHttpMessageConverter();
accessTokenResponseMessageConverter.setAccessTokenResponseConverter(parameters -> {
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build();
});
val accessTokenResponseMessageConverter = OAuth2AccessTokenResponseHttpMessageConverter()
accessTokenResponseMessageConverter.setAccessTokenResponseConverter { parameters ->
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build()
}

自定义错误处理

以下示例提供了自定义 Error 参数到OAuth2Error:spring-doc.cadn.net.cn

自定义 Access Token 错误处理程序
OAuth2ErrorHttpMessageConverter errorConverter =
	new OAuth2ErrorHttpMessageConverter();
errorConverter.setErrorConverter(parameters -> {
	// ...
	return new OAuth2Error("custom-error", "custom description", "custom-uri");
});

OAuth2ErrorResponseErrorHandler errorHandler =
	new OAuth2ErrorResponseErrorHandler();
errorHandler.setErrorConverter(errorConverter);
val errorConverter = OAuth2ErrorHttpMessageConverter()
errorConverter.setErrorConverter { parameters ->
	// ...
	return OAuth2Error("custom-error", "custom description", "custom-uri")
}

val errorHandler = OAuth2ErrorResponseErrorHandler()
errorHandler.setErrorConverter(errorConverter)

使用 Builder 进行自定义

无论您是否自定义RestClientJwtBearerTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您可以使用OAuth2AuthorizedClientProviderBuilder(作为发布 bean 的替代方法),如下所示:spring-doc.cadn.net.cn

通过 Builder 配置 Access Token 响应
// 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)

使用 Access Token

给定 OAuth 2.0 客户端注册的以下 Spring Boot 属性:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

@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如下:spring-doc.cadn.net.cn

@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解决Jwtassertion viaOAuth2AuthorizationContext.getPrincipal().getPrincipal()默认情况下,因此使用JwtAuthenticationToken在前面的示例中。spring-doc.cadn.net.cn

如果您需要解决Jwtassertion 的 Assertion 中,您可以提供JwtBearerOAuth2AuthorizedClientProvider.setJwtAssertionResolver()使用自定义Function<OAuth2AuthorizationContext, Jwt>.spring-doc.cadn.net.cn

代币兑换

请参阅 OAuth 2.0 Token Exchange,了解有关 Token Exchange 授权的更多详细信息。spring-doc.cadn.net.cn

申请 Access Token

请参阅 Token Exchange 请求和响应协议流程,了解 Token Exchange 授权。spring-doc.cadn.net.cn

有两种 implementation ofOAuth2AccessTokenResponseClient可用于向令牌端点发出 HTTP 请求,以获取令牌交换授权的访问令牌:spring-doc.cadn.net.cn

默认实现使用RestOperations实例,以在 Authorization Server 的令牌端点上交换访问令牌的授权代码。 Spring Security 6.4 引入了一个基于RestClient,它提供了类似的功能,但与组件的 Reactive 版本(基于WebClient),以便为任一堆栈上的应用程序提供一致的配置。spring-doc.cadn.net.cn

本节重点介绍RestClientTokenExchangeTokenResponseClient. 您可以阅读有关DefaultTokenExchangeTokenResponseClient在 Spring Security 6.3 文档中。spring-doc.cadn.net.cn

要选择使用RestClientTokenExchangeTokenResponseClient,只需提供一个 bean,如下例所示,它将被默认选取OAuth2AuthorizedClientManager自然而然:spring-doc.cadn.net.cn

Access Token 响应配置
@Bean
public OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient() {
	return new RestClientTokenExchangeTokenResponseClient();
}
@Bean
fun accessTokenResponseClient(): OAuth2AccessTokenResponseClient<Token Exchange> {
	return RestClientTokenExchangeTokenResponseClient()
}

新实现将是 Spring Security 7 中的默认值。spring-doc.cadn.net.cn

RestClientTokenExchangeTokenResponseClient非常灵活,并提供了多个选项来自定义 Token Exchange 授权的 OAuth 2.0 Access Token 请求和响应。 从以下使用案例中进行选择以了解更多信息:spring-doc.cadn.net.cn

自定义 Access Token 请求

RestClientTokenExchangeTokenResponseClient提供自定义 OAuth 2.0 Access Token Request 的 HTTP 头和请求参数的 hook。spring-doc.cadn.net.cn

自定义请求标头

自定义 HTTP 标头有两个选项:spring-doc.cadn.net.cn

您可以包含其他标头,而不会影响使用addHeadersConverter(). 以下示例添加了一个User-Agent标头添加到请求中时,registrationIdspring:spring-doc.cadn.net.cn

包括其他 HTTP 标头
RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
	new RestClientTokenExchangeTokenResponseClient();
accessTokenResponseClient.addHeadersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	HttpHeaders headers = new HttpHeaders();
	if (clientRegistration.getRegistrationId().equals("spring")) {
		headers.set(HttpHeaders.USER_AGENT, "my-user-agent");
	}
	return headers;
});
val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
accessTokenResponseClient.addHeadersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val headers = HttpHeaders()
	if (clientRegistration.getRegistrationId() == "spring") {
        headers[HttpHeaders.USER_AGENT] = "my-user-agent"
	}
	headers
}

您可以通过重复使用来完全自定义标头DefaultOAuth2TokenRequestHeadersConverter或使用setHeadersConverter(). 以下示例重用DefaultOAuth2TokenRequestHeadersConverter并禁用encodeClientCredentials,以便 HTTP Basic 凭证不再使用application/x-www-form-urlencoded:spring-doc.cadn.net.cn

自定义 HTTP 标头
DefaultOAuth2TokenRequestHeadersConverter headersConverter =
	new DefaultOAuth2TokenRequestHeadersConverter();
headersConverter.setEncodeClientCredentials(false);

RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
	new RestClientTokenExchangeTokenResponseClient();
accessTokenResponseClient.setHeadersConverter(headersConverter);
val headersConverter = DefaultOAuth2TokenRequestHeadersConverter()
headersConverter.setEncodeClientCredentials(false)

val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
accessTokenResponseClient.setHeadersConverter(headersConverter)

自定义请求参数

有三个选项可用于自定义请求参数:spring-doc.cadn.net.cn

setParametersConverter()不完全自定义参数,因为它需要用户自己提供所有默认参数。 默认参数始终提供,但可以通过调用setParametersCustomizer().spring-doc.cadn.net.cn

您可以包含其他参数,而不会影响使用addParametersConverter(). 以下示例添加了一个audience参数添加到请求中时,registrationIdkeycloak:spring-doc.cadn.net.cn

包括其他请求参数
RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
	new RestClientTokenExchangeTokenResponseClient();
accessTokenResponseClient.addParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
	if (clientRegistration.getRegistrationId().equals("keycloak")) {
		parameters.set(OAuth2ParameterNames.AUDIENCE, "my-audience");
	}
	return parameters;
});
val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
accessTokenResponseClient.addParametersConverter { grantRequest ->
	val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "keycloak") {
        parameters[OAuth2ParameterNames.AUDIENCE] = "my-audience"
	}
	parameters
}

您可以使用setParametersConverter(). 以下示例将client_id参数,当registrationIdokta:spring-doc.cadn.net.cn

覆盖请求参数
RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
	new RestClientTokenExchangeTokenResponseClient();
accessTokenResponseClient.setParametersConverter(grantRequest -> {
	ClientRegistration clientRegistration = grantRequest.getClientRegistration();
	LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
	if (clientRegistration.getRegistrationId().equals("okta")) {
		parameters.set(OAuth2ParameterNames.CLIENT_ID, "my-client");
	}
	return parameters;
});
val parametersConverter = DefaultOAuth2TokenRequestParametersConverter<TokenExchangeGrantRequest>()
parametersConverter.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
accessTokenResponseClient.setParametersConverter { grantRequest ->
    val clientRegistration = grantRequest.getClientRegistration()
	val parameters = LinkedMultiValueMap<String, String>()
	if (clientRegistration.getRegistrationId() == "okta") {
        parameters[OAuth2ParameterNames.CLIENT_ID] = "my-client"
	}
	parameters
}

您可以使用setParametersCustomizer(). 以下示例省略了client_id参数,当client_assertion参数:spring-doc.cadn.net.cn

省略请求参数
RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
	new RestClientTokenExchangeTokenResponseClient();
accessTokenResponseClient.setParametersCustomizer(parameters -> {
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID);
	}
});
val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
accessTokenResponseClient.setParametersCustomizer { parameters ->
	if (parameters.containsKey(OAuth2ParameterNames.CLIENT_ASSERTION)) {
		parameters.remove(OAuth2ParameterNames.CLIENT_ID)
	}
}

自定义访问令牌响应

RestClientTokenExchangeTokenResponseClient提供用于自定义响应参数和 OAuth 2.0 Access Token 响应错误处理的钩子。spring-doc.cadn.net.cn

自定义WebClient

您可以通过提供预配置的RestClientsetRestClient(). 默认的RestClient配置如下:spring-doc.cadn.net.cn

违约RestClient配置
RestClient restClient = RestClient.builder()
	.messageConverters(messageConverters -> {
		messageConverters.clear();
		messageConverters.add(new FormHttpMessageConverter());
		messageConverters.add(new OAuth2AccessTokenResponseHttpMessageConverter());
	})
	.defaultStatusHandler(new OAuth2ErrorResponseErrorHandler())
	.build();

RestClientTokenExchangeTokenResponseClient accessTokenResponseClient =
	new RestClientTokenExchangeTokenResponseClient();
accessTokenResponseClient.setRestClient(restClient);
val restClient = RestClient.builder()
	.messageConverters { messageConverters ->
		messageConverters.clear()
		messageConverters.add(FormHttpMessageConverter())
		messageConverters.add(OAuth2AccessTokenResponseHttpMessageConverter())
	}
	.defaultStatusHandler(OAuth2ErrorResponseErrorHandler())
	.build()

val accessTokenResponseClient = RestClientTokenExchangeTokenResponseClient()
accessTokenResponseClient.setRestClient(restClient)

OAuth2AccessTokenResponseHttpMessageConverter是一个HttpMessageConverter以获取 OAuth 2.0 访问令牌响应。 您可以自定义 Token Response 参数到OAuth2AccessTokenResponse通过调用setAccessTokenResponseConverter(). 默认实现为DefaultMapOAuth2AccessTokenResponseConverter.spring-doc.cadn.net.cn

OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler可以处理 OAuth 2.0 错误,例如400 Bad Request. 它使用OAuth2ErrorHttpMessageConverter用于将 OAuth 2.0 错误参数转换为OAuth2Error. 您可以自定义 Token Response 参数到OAuth2Error通过调用setErrorConverter().spring-doc.cadn.net.cn

Spring MVCFormHttpMessageConverter是必需的,因为它在发送 OAuth 2.0 访问令牌请求时使用。spring-doc.cadn.net.cn

自定义响应参数

以下示例提供了自定义 Token Response 参数转换为OAuth2AccessTokenResponse:spring-doc.cadn.net.cn

自定义 Access Token Response Converter
OAuth2AccessTokenResponseHttpMessageConverter accessTokenResponseMessageConverter =
	new OAuth2AccessTokenResponseHttpMessageConverter();
accessTokenResponseMessageConverter.setAccessTokenResponseConverter(parameters -> {
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build();
});
val accessTokenResponseMessageConverter = OAuth2AccessTokenResponseHttpMessageConverter()
accessTokenResponseMessageConverter.setAccessTokenResponseConverter { parameters ->
	// ...
	return OAuth2AccessTokenResponse.withToken("custom-token")
		// ...
		.build()
}

自定义错误处理

以下示例提供了自定义 Error 参数到OAuth2Error:spring-doc.cadn.net.cn

自定义 Access Token 错误处理程序
OAuth2ErrorHttpMessageConverter errorConverter =
	new OAuth2ErrorHttpMessageConverter();
errorConverter.setErrorConverter(parameters -> {
	// ...
	return new OAuth2Error("custom-error", "custom description", "custom-uri");
});

OAuth2ErrorResponseErrorHandler errorHandler =
	new OAuth2ErrorResponseErrorHandler();
errorHandler.setErrorConverter(errorConverter);
val errorConverter = OAuth2ErrorHttpMessageConverter()
errorConverter.setErrorConverter { parameters ->
	// ...
	return OAuth2Error("custom-error", "custom description", "custom-uri")
}

val errorHandler = OAuth2ErrorResponseErrorHandler()
errorHandler.setErrorConverter(errorConverter)

使用 Builder 进行自定义

无论您是否自定义RestClientTokenExchangeTokenResponseClient或提供您自己的OAuth2AccessTokenResponseClient,您可以使用OAuth2AuthorizedClientProviderBuilder(作为发布 bean 的替代方法),如下所示:spring-doc.cadn.net.cn

通过 Builder 配置 Access Token 响应
// 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)

使用 Access Token

给定 OAuth 2.0 客户端注册的以下 Spring Boot 属性:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

@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如下:spring-doc.cadn.net.cn

@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解析主题令牌(作为OAuth2Token) 通过OAuth2AuthorizationContext.getPrincipal().getPrincipal()默认情况下,因此使用JwtAuthenticationToken在前面的示例中。 默认情况下,不会解析角色令牌。spring-doc.cadn.net.cn

如果需要从其他来源解析主题令牌,可以提供TokenExchangeOAuth2AuthorizedClientProvider.setSubjectTokenResolver()使用自定义Function<OAuth2AuthorizationContext, OAuth2Token>.spring-doc.cadn.net.cn

如果需要解析 actor 令牌,可以提供TokenExchangeOAuth2AuthorizedClientProvider.setActorTokenResolver()使用自定义Function<OAuth2AuthorizationContext, OAuth2Token>.spring-doc.cadn.net.cn