协议端点
OAuth2 授权端点
OAuth2AuthorizationEndpointConfigurer 提供了自定义 OAuth2 授权端点 的能力。它定义了多个扩展点,允许您自定义 OAuth2 授权请求 的预处理、主处理和后处理逻辑。
OAuth2AuthorizationEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.authorizationEndpoint(authorizationEndpoint ->
authorizationEndpoint
.authorizationRequestConverter(authorizationRequestConverter) 1
.authorizationRequestConverters(authorizationRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.authorizationResponseHandler(authorizationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
.consentPage("/oauth2/v1/authorize") 7
)
);
return http.build();
}
authorizationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 OAuth2 授权请求(或同意)并将其转换为OAuth2AuthorizationCodeRequestAuthenticationToken或OAuth2AuthorizationConsentAuthenticationToken实例。authorizationRequestConverters(): 设置提供对默认及(可选)添加的AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于认证OAuth2AuthorizationCodeRequestAuthenticationToken或OAuth2AuthorizationConsentAuthenticationToken。authenticationProviders(): 设置提供对默认及(可选)添加的AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。authorizationResponseHandler(): 用于处理“已认证”的OAuth2AuthorizationCodeRequestAuthenticationToken并返回 OAuth2AuthorizationResponse 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthorizationCodeRequestAuthenticationException并返回 OAuth2Error 响应 的AuthenticationFailureHandler(后处理器)。consentPage(): 在授权请求流程中如果需要资源所有者同意,则将其重定向到的自定义同意页面的URI。
OAuth2AuthorizationEndpointConfigurer 用于配置 OAuth2AuthorizationEndpointFilter 并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2AuthorizationEndpointFilter 是处理 OAuth2 授权请求(及用户同意)的 Filter。
OAuth2AuthorizationEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个由OAuth2AuthorizationCodeRequestAuthenticationConverter和OAuth2AuthorizationConsentAuthenticationConverter组成的DelegatingAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2AuthorizationCodeRequestAuthenticationProvider和OAuth2AuthorizationConsentAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OAuth2AuthorizationCodeRequestAuthenticationToken并返回OAuth2AuthorizationResponse。 -
**AuthenticationFailureHandler**— 一个内部实现,使用与OAuth2AuthorizationCodeRequestAuthenticationException关联的OAuth2Error并返回OAuth2Error响应。
自定义授权请求验证
OAuth2AuthorizationCodeRequestAuthenticationValidator 是用于验证授权码许可流程中特定 OAuth2 授权请求参数的默认验证器。其默认实现会验证 redirect_uri 和 scope 参数。若验证失败,将抛出 OAuth2AuthorizationCodeRequestAuthenticationException 异常。
OAuth2AuthorizationCodeRequestAuthenticationProvider 提供了通过向 setAuthenticationValidator() 方法提供类型为 Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> 的自定义身份验证验证器,来覆盖默认授权请求验证的能力。
OAuth2AuthorizationCodeRequestAuthenticationContext 持有 OAuth2AuthorizationCodeRequestAuthenticationToken,该令牌包含了 OAuth2 授权请求参数。
如果验证失败,认证验证器必须抛出 OAuth2AuthorizationCodeRequestAuthenticationException。
在开发生命周期阶段,一个常见的用例是允许在 redirect_uri 参数中使用 localhost。
以下示例展示了如何配置 OAuth2AuthorizationCodeRequestAuthenticationProvider,通过自定义的身份验证验证器,允许在 redirect_uri 参数中使用 localhost:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.authorizationEndpoint(authorizationEndpoint ->
authorizationEndpoint
.authenticationProviders(configureAuthenticationValidator())
)
);
return http.build();
}
private Consumer<List<AuthenticationProvider>> configureAuthenticationValidator() {
return (authenticationProviders) ->
authenticationProviders.forEach((authenticationProvider) -> {
if (authenticationProvider instanceof OAuth2AuthorizationCodeRequestAuthenticationProvider) {
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator =
// Override default redirect_uri validator
new CustomRedirectUriValidator()
// Reuse default scope validator
.andThen(OAuth2AuthorizationCodeRequestAuthenticationValidator.DEFAULT_SCOPE_VALIDATOR);
((OAuth2AuthorizationCodeRequestAuthenticationProvider) authenticationProvider)
.setAuthenticationValidator(authenticationValidator);
}
});
}
static class CustomRedirectUriValidator implements Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> {
@Override
public void accept(OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext) {
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
authenticationContext.getAuthentication();
RegisteredClient registeredClient = authenticationContext.getRegisteredClient();
String requestedRedirectUri = authorizationCodeRequestAuthentication.getRedirectUri();
// Use exact string matching when comparing client redirect URIs against pre-registered URIs
if (!registeredClient.getRedirectUris().contains(requestedRedirectUri)) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, null);
}
}
}
OAuth2 推送式授权请求端点
OAuth2PushedAuthorizationRequestEndpointConfigurer 提供了自定义 OAuth2 推送授权请求端点 的能力。它定义了多个扩展点,允许您为 OAuth2 推送授权请求 自定义预处理、主处理和后处理逻辑。
OAuth2PushedAuthorizationRequestEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.pushedAuthorizationRequestEndpoint(pushedAuthorizationRequestEndpoint ->
pushedAuthorizationRequestEndpoint
.pushedAuthorizationRequestConverter(pushedAuthorizationRequestConverter) 1
.pushedAuthorizationRequestConverters(pushedAuthorizationRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.pushedAuthorizationResponseHandler(pushedAuthorizationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
);
return http.build();
}
pushedAuthorizationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 OAuth2 推送授权请求 并将其转换为OAuth2PushedAuthorizationRequestAuthenticationToken实例。pushedAuthorizationRequestConverters(): 设置提供对默认及(可选)添加的AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2PushedAuthorizationRequestAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认及(可选)添加的AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。pushedAuthorizationResponseHandler(): 用于处理“已认证”的OAuth2PushedAuthorizationRequestAuthenticationToken并返回 OAuth2 推送授权响应 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回 OAuth2Error 响应 的AuthenticationFailureHandler(后处理器)。
OAuth2PushedAuthorizationRequestEndpointConfigurer 用于配置 OAuth2PushedAuthorizationRequestEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2PushedAuthorizationRequestEndpointFilter 是处理 OAuth2 推送授权请求的 Filter。
OAuth2PushedAuthorizationRequestEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个由OAuth2AuthorizationCodeRequestAuthenticationConverter组成的DelegatingAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2PushedAuthorizationRequestAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OAuth2PushedAuthorizationRequestAuthenticationToken并返回 OAuth2 推送授权响应。 -
**AuthenticationFailureHandler**— 一个OAuth2ErrorAuthenticationFailureHandler。
自定义推送授权请求验证
OAuth2AuthorizationCodeRequestAuthenticationValidator 是用于验证授权码许可流程中特定 OAuth2 推送授权请求参数的默认验证器。其默认实现会验证 redirect_uri 和 scope 参数。若验证失败,将抛出 OAuth2AuthorizationCodeRequestAuthenticationException 异常。
OAuth2PushedAuthorizationRequestAuthenticationProvider 提供了通过向 setAuthenticationValidator() 方法提供类型为 Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> 的自定义认证验证器,来覆盖默认推送授权请求验证的能力。
OAuth2AuthorizationCodeRequestAuthenticationContext 持有 OAuth2AuthorizationCodeRequestAuthenticationToken,其中包含了 OAuth2 推送式授权请求参数。
如果验证失败,认证验证器必须抛出 OAuth2AuthorizationCodeRequestAuthenticationException。
在开发生命周期阶段,一个常见的用例是允许在 redirect_uri 参数中使用 localhost。
以下示例展示了如何配置 OAuth2PushedAuthorizationRequestAuthenticationProvider,并为其设置一个自定义的身份验证验证器,该验证器允许在 redirect_uri 参数中使用 localhost:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.pushedAuthorizationRequestEndpoint(pushedAuthorizationRequestEndpoint ->
pushedAuthorizationRequestEndpoint
.authenticationProviders(configureAuthenticationValidator())
)
);
return http.build();
}
private Consumer<List<AuthenticationProvider>> configureAuthenticationValidator() {
return (authenticationProviders) ->
authenticationProviders.forEach((authenticationProvider) -> {
if (authenticationProvider instanceof OAuth2PushedAuthorizationRequestAuthenticationProvider) {
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator =
// Override default redirect_uri validator
new CustomRedirectUriValidator()
// Reuse default scope validator
.andThen(OAuth2AuthorizationCodeRequestAuthenticationValidator.DEFAULT_SCOPE_VALIDATOR);
((OAuth2PushedAuthorizationRequestAuthenticationProvider) authenticationProvider)
.setAuthenticationValidator(authenticationValidator);
}
});
}
static class CustomRedirectUriValidator implements Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> {
@Override
public void accept(OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext) {
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
authenticationContext.getAuthentication();
RegisteredClient registeredClient = authenticationContext.getRegisteredClient();
String requestedRedirectUri = authorizationCodeRequestAuthentication.getRedirectUri();
// Use exact string matching when comparing client redirect URIs against pre-registered URIs
if (!registeredClient.getRedirectUris().contains(requestedRedirectUri)) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, null);
}
}
}
OAuth2 设备授权端点
OAuth2DeviceAuthorizationEndpointConfigurer 提供了自定义 OAuth2 设备授权端点 的能力。它定义了多个扩展点,允许您自定义 OAuth2 设备授权请求的预处理、主处理和后处理逻辑。
OAuth2DeviceAuthorizationEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.deviceAuthorizationEndpoint(deviceAuthorizationEndpoint ->
deviceAuthorizationEndpoint
.deviceAuthorizationRequestConverter(deviceAuthorizationRequestConverter) 1
.deviceAuthorizationRequestConverters(deviceAuthorizationRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.deviceAuthorizationResponseHandler(deviceAuthorizationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
.verificationUri("/oauth2/v1/device_verification") 7
)
);
return http.build();
}
deviceAuthorizationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 OAuth2 设备授权请求 并将其转换为OAuth2DeviceAuthorizationRequestAuthenticationToken实例。deviceAuthorizationRequestConverters(): 设置提供对默认及(可选)已添加的AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2DeviceAuthorizationRequestAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认及(可选)已添加的AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。deviceAuthorizationResponseHandler(): 用于处理“已认证”的OAuth2DeviceAuthorizationRequestAuthenticationToken并返回 OAuth2DeviceAuthorizationResponse 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回 OAuth2Error 响应 的AuthenticationFailureHandler(后处理器)。verificationUri(): 自定义终端用户验证页面的URI,用于在辅助设备上引导资源所有者。
默认情况下,OAuth2 设备授权端点处于禁用状态。
OAuth2DeviceAuthorizationEndpointConfigurer 用于配置 OAuth2DeviceAuthorizationEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2DeviceAuthorizationEndpointFilter 是处理 OAuth2 设备授权请求的 Filter。
OAuth2DeviceAuthorizationEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个OAuth2DeviceAuthorizationRequestAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2DeviceAuthorizationRequestAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OAuth2DeviceAuthorizationRequestAuthenticationToken并返回OAuth2DeviceAuthorizationResponse。 -
**AuthenticationFailureHandler**— 一个OAuth2ErrorAuthenticationFailureHandler。
OAuth2 设备验证端点
OAuth2DeviceVerificationEndpointConfigurer 提供了自定义 OAuth2 设备验证端点(或称“用户交互”)的能力。它定义了一系列扩展点,允许您自定义 OAuth2 设备验证请求的预处理、主处理和后处理逻辑。
OAuth2DeviceVerificationEndpointConfigurer 提供了以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.deviceVerificationEndpoint(deviceVerificationEndpoint ->
deviceVerificationEndpoint
.deviceVerificationRequestConverter(deviceVerificationRequestConverter) 1
.deviceVerificationRequestConverters(deviceVerificationRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.deviceVerificationResponseHandler(deviceVerificationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
.consentPage("/oauth2/v1/consent") 7
)
);
return http.build();
}
deviceVerificationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于在尝试从HttpServletRequest中提取 OAuth2 设备验证请求(或同意)时,将其转换为OAuth2DeviceVerificationAuthenticationToken或OAuth2DeviceAuthorizationConsentAuthenticationToken的实例。deviceVerificationRequestConverters(): 设置提供对默认(以及可选添加的)AuthenticationConverter列表访问的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2DeviceVerificationAuthenticationToken或OAuth2DeviceAuthorizationConsentAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认(以及可选添加的)AuthenticationProvider列表访问的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。deviceVerificationResponseHandler(): 用于处理“已认证”的OAuth2DeviceVerificationAuthenticationToken并引导资源所有者返回其设备的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回错误响应的AuthenticationFailureHandler(后处理器)。consentPage(): 在设备验证请求流程中如果需要同意,将资源所有者重定向到的自定义同意页面的URI。
默认情况下,OAuth2 设备验证端点处于禁用状态。
OAuth2DeviceVerificationEndpointConfigurer 用于配置 OAuth2DeviceVerificationEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2DeviceVerificationEndpointFilter 是处理 OAuth2 设备验证请求(及用户同意)的 Filter。
OAuth2DeviceVerificationEndpointFilter 配置了以下默认值:
-
**AuthenticationConverter**— 一个由OAuth2DeviceVerificationAuthenticationConverter和OAuth2DeviceAuthorizationConsentAuthenticationConverter组成的DelegatingAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2DeviceVerificationAuthenticationProvider和OAuth2DeviceAuthorizationConsentAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个SimpleUrlAuthenticationSuccessHandler,用于处理“已认证”的OAuth2DeviceVerificationAuthenticationToken并将用户重定向到成功页面(/?success)。 -
**AuthenticationFailureHandler**— 一个内部实现,使用与OAuth2AuthenticationException关联的OAuth2Error并返回OAuth2Error响应。
OAuth2 令牌端点
OAuth2TokenEndpointConfigurer 提供了自定义 OAuth2 令牌端点 的能力。它定义了多个扩展点,允许您自定义处理 OAuth2 访问令牌请求 的前置处理、主处理和后置处理逻辑。
OAuth2TokenEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.tokenEndpoint(tokenEndpoint ->
tokenEndpoint
.accessTokenRequestConverter(accessTokenRequestConverter) 1
.accessTokenRequestConverters(accessTokenRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.accessTokenResponseHandler(accessTokenResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
);
return http.build();
}
accessTokenRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 OAuth2 访问令牌请求 并将其转换为OAuth2AuthorizationGrantAuthenticationToken实例。accessTokenRequestConverters(): 设置提供对默认及(可选)添加的AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2AuthorizationGrantAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认及(可选)添加的AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。accessTokenResponseHandler(): 用于处理OAuth2AccessTokenAuthenticationToken并返回 OAuth2AccessTokenResponse 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回 OAuth2Error 响应 的AuthenticationFailureHandler(后处理器)。
OAuth2TokenEndpointConfigurer 用于配置 OAuth2TokenEndpointFilter 并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2TokenEndpointFilter 是处理 OAuth2 访问令牌请求的 Filter。
支持的 授权许可类型 包括 authorization_code、refresh_token、client_credentials、urn:ietf:params:oauth:grant-type:device_code 以及 urn:ietf:params:oauth:grant-type:token-exchange。
OAuth2TokenEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个由OAuth2AuthorizationCodeAuthenticationConverter、OAuth2RefreshTokenAuthenticationConverter、OAuth2ClientCredentialsAuthenticationConverter、OAuth2DeviceCodeAuthenticationConverter和OAuth2TokenExchangeAuthenticationConverter组成的DelegatingAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2AuthorizationCodeAuthenticationProvider、OAuth2RefreshTokenAuthenticationProvider、OAuth2ClientCredentialsAuthenticationProvider、OAuth2DeviceCodeAuthenticationProvider和OAuth2TokenExchangeAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个OAuth2AccessTokenResponseAuthenticationSuccessHandler。 -
**AuthenticationFailureHandler**— 一个OAuth2ErrorAuthenticationFailureHandler。
自定义客户端凭据授权请求验证
OAuth2ClientCredentialsAuthenticationValidator 是用于验证特定 OAuth2 客户端凭据授权请求参数的默认验证器。默认实现会验证 scope 参数。如果验证失败,将抛出 OAuth2AuthenticationException 异常。
OAuth2ClientCredentialsAuthenticationProvider 提供了通过向 setAuthenticationValidator() 方法提供类型为 Consumer<OAuth2ClientCredentialsAuthenticationContext> 的自定义身份验证验证器来覆盖默认请求验证的能力。
OAuth2ClientCredentialsAuthenticationContext 持有 OAuth2ClientCredentialsAuthenticationToken,其中包含了 OAuth2 客户端凭证授权请求的参数。
如果验证失败,认证验证器必须抛出 OAuth2AuthenticationException。
以下示例展示了如何配置 OAuth2ClientCredentialsAuthenticationProvider,并使用自定义的身份验证验证器来覆盖默认的 scope 验证:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.tokenEndpoint(tokenEndpoint ->
tokenEndpoint
.authenticationProviders(configureAuthenticationValidator())
)
);
return http.build();
}
private Consumer<List<AuthenticationProvider>> configureAuthenticationValidator() {
return (authenticationProviders) ->
authenticationProviders.forEach((authenticationProvider) -> {
if (authenticationProvider instanceof OAuth2ClientCredentialsAuthenticationProvider) {
Consumer<OAuth2ClientCredentialsAuthenticationContext> authenticationValidator =
new CustomScopeValidator();
// Override default scope validation
((OAuth2ClientCredentialsAuthenticationProvider) authenticationProvider)
.setAuthenticationValidator(authenticationValidator);
}
});
}
static class CustomScopeValidator implements Consumer<OAuth2ClientCredentialsAuthenticationContext> {
@Override
public void accept(OAuth2ClientCredentialsAuthenticationContext authenticationContext) {
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication =
authenticationContext.getAuthentication();
Set<String> requestedScopes = clientCredentialsAuthentication.getScopes();
RegisteredClient registeredClient = authenticationContext.getRegisteredClient();
Set<String> allowedScopes = registeredClient.getScopes();
// TODO Implement scope validation
}
}
DPoP绑定的访问令牌
RFC 9449 OAuth 2.0 持有证明演示 (DPoP) 是一种用于对访问令牌进行发送方约束的应用层机制。
DPoP的主要目标是通过在授权服务器颁发访问令牌时将其与公钥绑定,并要求客户端在资源服务器使用访问令牌时证明其拥有对应的私钥,从而防止未经授权或非法的客户端使用泄露或被盗的访问令牌。
通过DPoP进行发送方约束的访问令牌与典型的承载令牌形成对比,后者可由任何持有该访问令牌的客户端使用。
DPoP引入了DPoP证明的概念,这是一种由客户端创建的 JWT,并作为 HTTP 请求的头部发送。客户端使用 DPoP 证明来证明其拥有与某个公钥相对应的私钥。
当客户端发起访问令牌请求时,会在HTTP请求头中附加一个DPoP证明。授权服务器将访问令牌与DPoP证明中的公钥进行绑定(发送方约束)。
当客户端发起受保护资源请求时,它会在HTTP头部再次附加一个DPoP证明。
资源服务器获取与访问令牌绑定的公钥信息,该信息可直接从访问令牌(JWT)中获取,或通过 OAuth2令牌自省端点 获取。随后,资源服务器验证访问令牌绑定的公钥是否与 DPoP 证明中的公钥匹配,同时验证 DPoP 证明中的访问令牌哈希值是否与请求中的访问令牌一致。
DPoP 访问令牌请求
要请求一个与公钥绑定的访问令牌(使用DPoP),客户端在向OAuth2令牌端点发起访问令牌请求时,必须在DPoP头部提供一个有效的DPoP证明。这适用于所有访问令牌请求,无论授权许可类型如何(例如authorization_code、refresh_token、client_credentials等)。
以下HTTP请求展示了在DPoP头部包含DPoP证明的authorization_code访问令牌请求:
POST /oauth2/token HTTP/1.1
Host: server.example.com
Content-Type: application/x-www-form-urlencoded
DPoP: eyJraWQiOiJyc2EtandrLWtpZCIsInR5cCI6ImRwb3Arand0IiwiYWxnIjoiUlMyNTYiLCJqd2siOnsia3R5IjoiUlNBIiwiZSI6IkFRQUIiLCJraWQiOiJyc2EtandrLWtpZCIsIm4iOiIzRmxxSnI1VFJza0lRSWdkRTNEZDdEOWxib1dkY1RVVDhhLWZKUjdNQXZRbTdYWE5vWWttM3Y3TVFMMU5ZdER2TDJsOENBbmMwV2RTVElOVTZJUnZjNUtxbzJRNGNzTlg5U0hPbUVmem9ST2pRcWFoRWN2ZTFqQlhsdW9DWGRZdVlweDRfMXRmUmdHNmlpNFVoeGg2aUk4cU5NSlFYLWZMZnFoYmZZZnhCUVZSUHl3QmtBYklQNHgxRUFzYkM2RlNObWtoQ3hpTU5xRWd4YUlwWThDMmtKZEpfWklWLVdXNG5vRGR6cEtxSGN3bUI4RnNydW1sVllfRE5WdlVTRElpcGlxOVBiUDRIOTlUWE4xbzc0Nm9SYU5hMDdycTFob0NnTVNTeS04NVNhZ0NveGxteUUtRC1vZjlTc01ZOE9sOXQwcmR6cG9iQnVoeUpfbzVkZnZqS3cifX0.eyJodG0iOiJQT1NUIiwiaHR1IjoiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20vb2F1dGgyL3Rva2VuIiwiaWF0IjoxNzQ2ODA2MzA1LCJqdGkiOiI0YjIzNDBkMi1hOTFmLTQwYTUtYmFhOS1kZDRlNWRlYWM4NjcifQ.wq8gJ_G6vpiEinfaY3WhereqCCLoeJOG8tnWBBAzRWx9F1KU5yAAWq-ZVCk_k07-h6DIqz2wgv6y9dVbNpRYwNwDUeik9qLRsC60M8YW7EFVyI3n_NpujLwzZeub_nDYMVnyn4ii0NaZrYHtoGXOlswQfS_-ET-jpC0XWm5nBZsCdUEXjOYtwaACC6Js-pyNwKmSLp5SKIk11jZUR5xIIopaQy521y9qJHhGRwzj8DQGsP7wMZ98UFL0E--1c-hh4rTy8PMeWCqRHdwjj_ry_eTe0DJFcxxYQdeL7-0_0CIO4Ayx5WHEpcUOIzBRoN32RsNpDZc-5slDNj9ku004DA
grant_type=authorization_code\
&client_id=s6BhdRkqt\
&code=SplxlOBeZQQYbYS6WxSbIA\
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb\
&code_verifier=bEaL42izcC-o-xBk0K2vuJ6U-y1p9r_wW2dFWIWgjz-
以下展示了 DPoP Proof JWT 的头部和声明表示:
{
"typ": "dpop+jwt",
"alg": "RS256",
"jwk": {
"kty": "RSA",
"e": "AQAB",
"n": "3FlqJr5TRskIQIgdE3Dd7D9lboWdcTUT8a-fJR7MAvQm7XXNoYkm3v7MQL1NYtDvL2l8CAnc0WdSTINU6IRvc5Kqo2Q4csNX9SHOmEfzoROjQqahEcve1jBXluoCXdYuYpx4_1tfRgG6ii4Uhxh6iI8qNMJQX-fLfqhbfYfxBQVRPywBkAbIP4x1EAsbC6FSNmkhCxiMNqEgxaIpY8C2kJdJ_ZIV-WW4noDdzpKqHcwmB8FsrumlVY_DNVvUSDIipiq9PbP4H99TXN1o746oRaNa07rq1hoCgMSSy-85SagCoxlmyE-D-of9SsMY8Ol9t0rdzpobBuhyJ_o5dfvjKw"
}
}
{
"htm": "POST",
"htu": "https://server.example.com/oauth2/token",
"iat": 1746806305,
"jti": "4b2340d2-a91f-40a5-baa9-dd4e5deac867"
}
以下代码展示了如何生成 DPoP Proof JWT 的示例:
RSAKey rsaKey = ...
JWKSource<SecurityContext> jwkSource = (jwkSelector, securityContext) -> jwkSelector
.select(new JWKSet(rsaKey));
NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256)
.type("dpop+jwt")
.jwk(rsaKey.toPublicJWK().toJSONObject())
.build();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(Instant.now())
.claim("htm", "POST")
.claim("htu", "https://server.example.com/oauth2/token")
.id(UUID.randomUUID().toString())
.build();
Jwt dPoPProof = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims));
当授权服务器成功验证DPoP证明后,来自DPoP证明的公钥将被绑定(发送方约束)到所颁发的访问令牌上。
以下访问令牌响应展示了 token_type 参数为 DPoP,以此向客户端表明该访问令牌已与其 DPoP 证明公钥绑定:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token": "Kz~8mXK1EalYznwH-LC-1fBAo.4Ljp~zsPE_NeO.gxU",
"token_type": "DPoP",
"expires_in": 2677
}
公钥确认
资源服务器必须能够识别访问令牌是否与DPoP绑定,并验证其与DPoP证明公钥的绑定关系。这种绑定是通过将公钥与访问令牌关联起来实现的,以便资源服务器能够访问,例如直接将公钥哈希嵌入访问令牌(JWT)中,或通过令牌自省(token introspection)实现。
当访问令牌以JWT形式表示时,公钥哈希包含在确认方法(cnf)声明下的 jkt 声明中。
以下示例展示了一个JWT访问令牌的声明,其中包含带有jkt声明的cnf声明,该jkt声明即为DPoP证明公钥的JWK SHA-256指纹:
{
"sub":"user@example.com",
"iss":"https://server.example.com",
"nbf":1562262611,
"exp":1562266216,
"cnf":
{
"jkt":"CQMknzRoZ5YUi7vS58jck1q8TmZT8wiIiXrCN1Ny4VU"
}
}
OAuth2令牌内省端点
OAuth2TokenIntrospectionEndpointConfigurer 提供了自定义 OAuth2 Token Introspection 端点 的能力。它定义了扩展点,允许您自定义 OAuth2 内省请求 的预处理、主处理和后处理逻辑。
OAuth2TokenIntrospectionEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.tokenIntrospectionEndpoint(tokenIntrospectionEndpoint ->
tokenIntrospectionEndpoint
.introspectionRequestConverter(introspectionRequestConverter) 1
.introspectionRequestConverters(introspectionRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.introspectionResponseHandler(introspectionResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
);
return http.build();
}
introspectionRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 OAuth2 内省请求 并将其转换为OAuth2TokenIntrospectionAuthenticationToken实例。introspectionRequestConverters(): 设置提供对默认(以及可选添加的)AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2TokenIntrospectionAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认(以及可选添加的)AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。introspectionResponseHandler(): 用于处理“已认证”的OAuth2TokenIntrospectionAuthenticationToken并返回 OAuth2TokenIntrospection 响应 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回 OAuth2Error 响应 的AuthenticationFailureHandler(后处理器)。
OAuth2TokenIntrospectionEndpointConfigurer 用于配置 OAuth2TokenIntrospectionEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2TokenIntrospectionEndpointFilter 是处理 OAuth2 令牌内省请求的 Filter。
OAuth2TokenIntrospectionEndpointFilter 配置了以下默认值:
-
**AuthenticationConverter**— 一个OAuth2TokenIntrospectionAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2TokenIntrospectionAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OAuth2TokenIntrospectionAuthenticationToken并返回OAuth2TokenIntrospection响应。 -
**AuthenticationFailureHandler**— 一个OAuth2ErrorAuthenticationFailureHandler。
OAuth2 令牌撤销端点
OAuth2TokenRevocationEndpointConfigurer 提供了自定义 OAuth2 令牌撤销端点 的能力。它定义了多个扩展点,允许您自定义 OAuth2 撤销请求 的预处理、主处理和后处理逻辑。
OAuth2TokenRevocationEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.tokenRevocationEndpoint(tokenRevocationEndpoint ->
tokenRevocationEndpoint
.revocationRequestConverter(revocationRequestConverter) 1
.revocationRequestConverters(revocationRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.revocationResponseHandler(revocationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
);
return http.build();
}
revocationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 OAuth2 撤销请求 并将其转换为OAuth2TokenRevocationAuthenticationToken实例。revocationRequestConverters(): 设置提供对默认(以及可选添加的)AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2TokenRevocationAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认(以及可选添加的)AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。revocationResponseHandler(): 用于处理“已认证”的OAuth2TokenRevocationAuthenticationToken并返回 OAuth2 撤销响应 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回 OAuth2Error 响应 的AuthenticationFailureHandler(后处理器)。
OAuth2TokenRevocationEndpointConfigurer 用于配置 OAuth2TokenRevocationEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2TokenRevocationEndpointFilter 是处理 OAuth2 撤销请求的 Filter。
OAuth2TokenRevocationEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个OAuth2TokenRevocationAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2TokenRevocationAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OAuth2TokenRevocationAuthenticationToken并返回 OAuth2 撤销响应。 -
**AuthenticationFailureHandler**— 一个OAuth2ErrorAuthenticationFailureHandler。
OAuth2 客户端注册端点
OAuth2ClientRegistrationEndpointConfigurer 提供了自定义 OAuth2 客户端注册端点 的能力。它定义了多个扩展点,允许您为 客户端注册请求 自定义预处理、主处理和后处理逻辑。
OAuth2ClientRegistrationEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.clientRegistrationEndpoint(clientRegistrationEndpoint ->
clientRegistrationEndpoint
.clientRegistrationRequestConverter(clientRegistrationRequestConverter) 1
.clientRegistrationRequestConverters(clientRegistrationRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.clientRegistrationResponseHandler(clientRegistrationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
);
return http.build();
}
clientRegistrationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取客户端注册请求并将其转换为OAuth2ClientRegistrationAuthenticationToken实例。clientRegistrationRequestConverters(): 设置一个Consumer,提供对默认(以及可选添加的)AuthenticationConverter列表的访问,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OAuth2ClientRegistrationAuthenticationToken进行身份验证。authenticationProviders(): 设置一个Consumer,提供对默认(以及可选添加的)AuthenticationProvider列表的访问,允许添加、移除或自定义特定的AuthenticationProvider。clientRegistrationResponseHandler(): 用于处理“已认证”的OAuth2ClientRegistrationAuthenticationToken并返回客户端注册响应的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回客户端注册错误响应的AuthenticationFailureHandler(后处理器)。
默认情况下,OAuth2 客户端注册端点处于禁用状态。
OAuth2ClientRegistrationEndpointConfigurer 用于配置 OAuth2ClientRegistrationEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2ClientRegistrationEndpointFilter 是一个 Filter,它处理客户端注册请求并返回OAuth2ClientRegistration 响应。
OAuth2ClientRegistrationEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个OAuth2ClientRegistrationAuthenticationConverter。 -
**AuthenticationManager**— 一个由OAuth2ClientRegistrationAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OAuth2ClientRegistrationAuthenticationToken并返回OAuth2ClientRegistration响应。 -
**AuthenticationFailureHandler**— 一个内部实现,使用与OAuth2AuthenticationException关联的OAuth2Error并返回OAuth2Error响应。
OAuth2 客户端注册端点是一个 OAuth2 受保护资源,要求在客户端注册请求中将访问令牌作为承载令牌发送。
OAuth2 资源服务器支持已自动配置,但 OAuth2 客户端注册端点需要一个 JwtDecoder @Bean。
客户端注册请求中的访问令牌必须包含 OAuth2 范围 client.create。
:::提示
要允许开放客户端注册(请求中不包含访问令牌),请配置 OAuth2ClientRegistrationAuthenticationProvider.setOpenRegistrationAllowed(true)。
:::
OAuth2 授权服务器元数据端点
OAuth2AuthorizationServerMetadataEndpointConfigurer 提供了自定义 OAuth2 授权服务器元数据端点 的能力。它定义了一个扩展点,允许您自定义 OAuth2 授权服务器元数据响应。
OAuth2AuthorizationServerMetadataEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.authorizationServerMetadataEndpoint(authorizationServerMetadataEndpoint ->
authorizationServerMetadataEndpoint
.authorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer) 1
)
);
return http.build();
}
authorizationServerMetadataCustomizer(): 提供对OAuth2AuthorizationServerMetadata.Builder访问的Consumer,允许自定义授权服务器配置的声明。
OAuth2AuthorizationServerMetadataEndpointConfigurer 用于配置 OAuth2AuthorizationServerMetadataEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OAuth2AuthorizationServerMetadataEndpointFilter 是一个 Filter,负责返回 OAuth2AuthorizationServerMetadata 响应。
JWK 集端点
OAuth2AuthorizationServerConfigurer 为 JWK Set 端点 提供支持。
OAuth2AuthorizationServerConfigurer 配置了 NimbusJwkSetEndpointFilter 并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。NimbusJwkSetEndpointFilter 是返回 JWK 集 的 Filter。
仅当注册了 JWKSource<SecurityContext> @Bean 时,才会配置 JWK Set 端点。
OpenID Connect 1.0 提供方配置端点
OidcProviderConfigurationEndpointConfigurer 提供了自定义 OpenID Connect 1.0 提供方配置端点 的能力。它定义了一个扩展点,允许您自定义 OpenID 提供方配置响应。
OidcProviderConfigurationEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.oidc(oidc ->
oidc
.providerConfigurationEndpoint(providerConfigurationEndpoint ->
providerConfigurationEndpoint
.providerConfigurationCustomizer(providerConfigurationCustomizer) 1
)
)
);
return http.build();
}
providerConfigurationCustomizer(): 提供访问OidcProviderConfiguration.Builder的Consumer,允许自定义 OpenID Provider 配置的声明。
OidcProviderConfigurationEndpointConfigurer 用于配置 OidcProviderConfigurationEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OidcProviderConfigurationEndpointFilter 是一个 Filter,负责返回 OidcProviderConfiguration 响应。
OpenID Connect 1.0 注销端点
OidcLogoutEndpointConfigurer 提供了自定义 OpenID Connect 1.0 注销端点 的能力。它定义了多个扩展点,允许你为 RP-Initiated 注销请求定制预处理、主处理和后处理逻辑。
OidcLogoutEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.oidc(oidc ->
oidc
.logoutEndpoint(logoutEndpoint ->
logoutEndpoint
.logoutRequestConverter(logoutRequestConverter) 1
.logoutRequestConverters(logoutRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.logoutResponseHandler(logoutResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
)
);
return http.build();
}
logoutRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于在尝试从HttpServletRequest中提取 Logout 请求 并将其转换为OidcLogoutAuthenticationToken实例时使用。logoutRequestConverters(): 设置提供对默认及(可选)添加的AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OidcLogoutAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认及(可选)添加的AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。logoutResponseHandler(): 用于处理“已认证”的OidcLogoutAuthenticationToken并执行注销的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回错误响应的AuthenticationFailureHandler(后处理器)。
OidcLogoutEndpointConfigurer 用于配置 OidcLogoutEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OidcLogoutEndpointFilter 是一个 Filter,它处理 RP-Initiated Logout 请求 并执行终端用户的注销操作。
OidcLogoutEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个OidcLogoutAuthenticationConverter。 -
**AuthenticationManager**— 一个由OidcLogoutAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个OidcLogoutAuthenticationSuccessHandler。 -
**AuthenticationFailureHandler**— 一个内部实现,它使用与OAuth2AuthenticationException关联的OAuth2Error并返回OAuth2Error响应。
OidcLogoutAuthenticationProvider 使用 SessionRegistry 来查找与请求注销的终端用户相关联的 SessionInformation 实例。
OidcClientInitiatedLogoutSuccessHandler 是 Spring Security OAuth2 客户端支持中用于配置 OpenID Connect 1.0 RP-Initiated 登出 的对应配置。
自定义注销请求验证
OidcLogoutAuthenticationValidator 是用于验证特定 OpenID Connect RP-Initiated 注销请求参数的默认验证器。其默认实现会验证 post_logout_redirect_uri 参数。如果验证失败,将抛出 OAuth2AuthenticationException 异常。
OidcLogoutAuthenticationProvider 提供了通过向 setAuthenticationValidator() 方法提供类型为 Consumer<OidcLogoutAuthenticationContext> 的自定义认证验证器,来覆盖默认登出请求验证的能力。
OidcLogoutAuthenticationContext 持有 OidcLogoutAuthenticationToken,其中包含了注销请求的参数。
如果验证失败,身份验证验证器必须抛出 OAuth2AuthenticationException。
以下示例展示了如何配置 OidcLogoutAuthenticationProvider 并为其设置自定义的身份验证验证器:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.oidc(oidc ->
oidc
.logoutEndpoint(logoutEndpoint ->
logoutEndpoint
.authenticationProviders(configureAuthenticationValidator())
)
)
);
return http.build();
}
private Consumer<List<AuthenticationProvider>> configureAuthenticationValidator() {
return (authenticationProviders) ->
authenticationProviders.forEach((authenticationProvider) -> {
if (authenticationProvider instanceof OidcLogoutAuthenticationProvider oidcLogoutAuthenticationProvider) {
Consumer<OidcLogoutAuthenticationContext> authenticationValidator = new CustomPostLogoutRedirectUriValidator();
oidcLogoutAuthenticationProvider.setAuthenticationValidator(authenticationValidator);
}
});
}
static class CustomPostLogoutRedirectUriValidator implements Consumer<OidcLogoutAuthenticationContext> {
@Override
public void accept(OidcLogoutAuthenticationContext authenticationContext) {
OidcLogoutAuthenticationToken oidcLogoutAuthentication =
authenticationContext.getAuthentication();
RegisteredClient registeredClient = authenticationContext.getRegisteredClient();
// TODO
}
}
OpenID Connect 1.0 用户信息端点
OidcUserInfoEndpointConfigurer 提供了自定义 OpenID Connect 1.0 UserInfo 端点 的能力。它定义了多个扩展点,允许您为 UserInfo 请求 自定义预处理、主处理和后处理逻辑。
OidcUserInfoEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.oidc(oidc ->
oidc
.userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint
.userInfoRequestConverter(userInfoRequestConverter) 1
.userInfoRequestConverters(userInfoRequestConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.userInfoResponseHandler(userInfoResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
.userInfoMapper(userInfoMapper) 7
)
)
);
return http.build();
}
userInfoRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取 UserInfo 请求 并将其转换为OidcUserInfoAuthenticationToken实例。userInfoRequestConverters(): 设置提供对默认及(可选)添加的AuthenticationConverter列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OidcUserInfoAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认及(可选)添加的AuthenticationProvider列表访问权限的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。userInfoResponseHandler(): 用于处理“已认证”的OidcUserInfoAuthenticationToken并返回 UserInfo 响应 的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回 UserInfo 错误响应 的AuthenticationFailureHandler(后处理器)。userInfoMapper(): 用于从OidcUserInfoAuthenticationContext中提取声明到OidcUserInfo实例的Function。
OidcUserInfoEndpointConfigurer 用于配置 OidcUserInfoEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OidcUserInfoEndpointFilter 是一个 Filter,它处理 UserInfo 请求并返回 OidcUserInfo 响应。
OidcUserInfoEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个内部实现,用于从SecurityContext中获取Authentication,并使用主体创建一个OidcUserInfoAuthenticationToken。 -
**AuthenticationManager**— 一个由OidcUserInfoAuthenticationProvider组成的AuthenticationManager,它与userInfoMapper的内部实现相关联,该实现根据授权期间请求的作用域,从ID Token 中提取标准声明。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OidcUserInfoAuthenticationToken并返回OidcUserInfo响应。 -
**AuthenticationFailureHandler**— 一个内部实现,它使用与OAuth2AuthenticationException关联的OAuth2Error并返回OAuth2Error响应。
你可以通过提供一个 OAuth2TokenCustomizer<JwtEncodingContext> @Bean 来自定义 ID Token。
OpenID Connect 1.0 用户信息端点是一个 OAuth2 受保护资源,要求在用户信息请求中将访问令牌作为承载令牌发送。
OAuth2 资源服务器支持已自动配置,但 OpenID Connect 1.0 UserInfo 端点需要一个 JwtDecoder @Bean。
OpenID Connect 1.0 客户端注册端点
OidcClientRegistrationEndpointConfigurer 提供了自定义 OpenID Connect 1.0 客户端注册端点 的能力。它定义了一些扩展点,允许您为 客户端注册请求 或 客户端读取请求 自定义预处理、主处理和后处理逻辑。
OidcClientRegistrationEndpointConfigurer 提供以下配置选项:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.oidc(oidc ->
oidc
.clientRegistrationEndpoint(clientRegistrationEndpoint ->
clientRegistrationEndpoint
.clientRegistrationRequestConverter(clientRegistrationRequestConverter) 1
.clientRegistrationRequestConverters(clientRegistrationRequestConvertersConsumers) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.clientRegistrationResponseHandler(clientRegistrationResponseHandler) 5
.errorResponseHandler(errorResponseHandler) 6
)
)
);
return http.build();
}
clientRegistrationRequestConverter(): 添加一个AuthenticationConverter(预处理器),用于尝试从HttpServletRequest中提取客户端注册请求或客户端读取请求到OidcClientRegistrationAuthenticationToken实例。clientRegistrationRequestConverters(): 设置提供对默认(以及可选添加的)AuthenticationConverter列表访问的Consumer,允许添加、移除或自定义特定的AuthenticationConverter。authenticationProvider(): 添加一个AuthenticationProvider(主处理器),用于对OidcClientRegistrationAuthenticationToken进行身份验证。authenticationProviders(): 设置提供对默认(以及可选添加的)AuthenticationProvider列表访问的Consumer,允许添加、移除或自定义特定的AuthenticationProvider。clientRegistrationResponseHandler(): 用于处理“已认证”的OidcClientRegistrationAuthenticationToken并返回客户端注册响应或客户端读取响应的AuthenticationSuccessHandler(后处理器)。errorResponseHandler(): 用于处理OAuth2AuthenticationException并返回客户端注册错误响应或客户端读取错误响应的AuthenticationFailureHandler(后处理器)。
OpenID Connect 1.0 客户端注册端点默认处于禁用状态。
OidcClientRegistrationEndpointConfigurer 用于配置 OidcClientRegistrationEndpointFilter,并将其注册到 OAuth2 授权服务器的 SecurityFilterChain @Bean 中。OidcClientRegistrationEndpointFilter 是一个 Filter,它处理客户端注册请求并返回 OidcClientRegistration 响应。
OidcClientRegistrationEndpointFilter 同样处理客户端读取请求并返回OidcClientRegistration 响应。
OidcClientRegistrationEndpointFilter 配置了以下默认设置:
-
**AuthenticationConverter**— 一个OidcClientRegistrationAuthenticationConverter。 -
**AuthenticationManager**— 一个由OidcClientRegistrationAuthenticationProvider和OidcClientConfigurationAuthenticationProvider组成的AuthenticationManager。 -
**AuthenticationSuccessHandler**— 一个内部实现,用于处理“已认证”的OidcClientRegistrationAuthenticationToken并返回OidcClientRegistration响应。 -
**AuthenticationFailureHandler**— 一个内部实现,它使用与OAuth2AuthenticationException关联的OAuth2Error并返回OAuth2Error响应。
OpenID Connect 1.0 客户端注册端点是一个 OAuth2 受保护资源,要求在客户端注册(或客户端读取)请求中将访问令牌作为承载令牌发送。
OAuth2 资源服务器支持已自动配置,但 OpenID Connect 1.0 客户端注册端点需要一个 JwtDecoder @Bean。
客户端注册请求中的访问令牌必须包含 OAuth2 范围 client.create。
客户端读取请求中的访问令牌必须包含 OAuth2 范围 client.read。