Configuration Model
Default configuration
OAuth2AuthorizationServerConfiguration
是一个 @Configuration
,它为 OAuth2 授权服务器提供最小的默认配置。
OAuth2AuthorizationServerConfiguration
is a @Configuration
that provides the minimal default configuration for an OAuth2 authorization server.
OAuth2AuthorizationServerConfiguration
使用 OAuth2AuthorizationServerConfigurer
来应用默认配置,并注册一个 SecurityFilterChain
@Bean
,其中包括支持一个 OAuth2 授权服务器的所有基础架构组件。
OAuth2AuthorizationServerConfiguration
uses OAuth2AuthorizationServerConfigurer
to apply the default configuration and registers a SecurityFilterChain
@Bean
composed of all the infrastructure components supporting an OAuth2 authorization server.
|
|
OAuth2 授权服务器 SecurityFilterChain
@Bean
使用以下默认协议端点配置:
The OAuth2 authorization server SecurityFilterChain
@Bean
is configured with the following default protocol endpoints:
如果一个 |
The JWK Set endpoint is configured only if a |
以下示例演示如何使用 OAuth2AuthorizationServerConfiguration
应用最小的默认配置:
The following example shows how to use OAuth2AuthorizationServerConfiguration
to apply the minimal default configuration:
@Configuration
@Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthorizationServerConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
List<RegisteredClient> registrations = ...
return new InMemoryRegisteredClientRepository(registrations);
}
@Bean
public JWKSource<SecurityContext> jwkSource() {
RSAKey rsaKey = ...
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
}
authorization_code grant 要求资源所有者已通过身份验证。因此,除了默认的 OAuth2 安全配置之外,还需要配置一个用户身份验证机制 must。
The authorization_code grant requires the resource owner to be authenticated. Therefore, a user authentication mechanism must be configured in addition to the default OAuth2 security configuration.
在默认配置中禁用了 OpenID Connect 1.0。以下示例展示了如何通过初始化`OidcConfigurer`来启用OpenID Connect 1.0:
OpenID Connect 1.0 is disabled in the default configuration. The following example shows how to enable OpenID Connect 1.0 by initializing the OidcConfigurer
:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(Customizer.withDefaults()); // Initialize `OidcConfigurer`
return http.build();
}
除了默认协议端点外,OAuth2 授权服务器 SecurityFilterChain
@Bean
还使用以下 OpenID Connect 1.0 协议端点配置:
In addition to the default protocol endpoints, the OAuth2 authorization server SecurityFilterChain
@Bean
is configured with the following OpenID Connect 1.0 protocol endpoints:
默认情况下,OpenID Connect 1.0 Client Registration endpoint 被禁用,因为许多部署不需要动态客户端注册。 |
The OpenID Connect 1.0 Client Registration endpoint is disabled by default because many deployments do not require dynamic client registration. |
|
|
以下示例演示如何注册一个 JwtDecoder
@Bean
:
The following example shows how to register a JwtDecoder
@Bean
:
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
}
OAuth2AuthorizationServerConfiguration
的主要目的是提供一种方便的方法来应用 OAuth2 授权服务器的最小的默认配置。不过,在大多数情况下,需要自定义配置。
The main intent of OAuth2AuthorizationServerConfiguration
is to provide a convenient method to apply the minimal default configuration for an OAuth2 authorization server. However, in most cases, customizing the configuration will be required.
Customizing the configuration
OAuth2AuthorizationServerConfigurer
提供完全自定义针对 OAuth2 授权服务器的安全配置的能力。它允许你指定要使用的核心组件——例如 RegisteredClientRepository
,OAuth2AuthorizationService
,OAuth2TokenGenerator
等等。此外,它允许你自定义针对协议端点的请求处理逻辑——例如 authorization endpoint,device authorization endpoint,device verification endpoint,token endpoint,token introspection endpoint等等。
OAuth2AuthorizationServerConfigurer
provides the ability to fully customize the security configuration for an OAuth2 authorization server.
It lets you specify the core components to use - for example, RegisteredClientRepository
, OAuth2AuthorizationService
, OAuth2TokenGenerator
, and others.
Furthermore, it lets you customize the request processing logic for the protocol endpoints – for example, authorization endpoint, device authorization endpoint, device verification endpoint, token endpoint, token introspection endpoint, and others.
OAuth2AuthorizationServerConfigurer
提供以下配置选项:
OAuth2AuthorizationServerConfigurer
provides the following configuration options:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer();
http.apply(authorizationServerConfigurer);
authorizationServerConfigurer
.registeredClientRepository(registeredClientRepository) 1
.authorizationService(authorizationService) 2
.authorizationConsentService(authorizationConsentService) 3
.authorizationServerSettings(authorizationServerSettings) 4
.tokenGenerator(tokenGenerator) 5
.clientAuthentication(clientAuthentication -> { }) 6
.authorizationEndpoint(authorizationEndpoint -> { }) 7
.deviceAuthorizationEndpoint(deviceAuthorizationEndpoint -> { }) 8
.deviceVerificationEndpoint(deviceVerificationEndpoint -> { }) 9
.tokenEndpoint(tokenEndpoint -> { }) 10
.tokenIntrospectionEndpoint(tokenIntrospectionEndpoint -> { }) 11
.tokenRevocationEndpoint(tokenRevocationEndpoint -> { }) 12
.authorizationServerMetadataEndpoint(authorizationServerMetadataEndpoint -> { }) 13
.oidc(oidc -> oidc
.providerConfigurationEndpoint(providerConfigurationEndpoint -> { }) 14
.logoutEndpoint(logoutEndpoint -> { }) 15
.userInfoEndpoint(userInfoEndpoint -> { }) 16
.clientRegistrationEndpoint(clientRegistrationEndpoint -> { }) 17
);
return http.build();
}
1 | registeredClientRepository() : The RegisteredClientRepository (REQUIRED) for managing new and existing clients. |
2 | authorizationService() : The OAuth2AuthorizationService for managing new and existing authorizations. |
3 | authorizationConsentService() : The OAuth2AuthorizationConsentService for managing new and existing authorization consents. |
4 | authorizationServerSettings() : The AuthorizationServerSettings (REQUIRED) for customizing configuration settings for the OAuth2 authorization server. |
5 | tokenGenerator() : The OAuth2TokenGenerator for generating tokens supported by the OAuth2 authorization server. |
6 | clientAuthentication() : The configurer for OAuth2 Client Authentication. |
7 | authorizationEndpoint() : The configurer for the OAuth2 Authorization endpoint. |
8 | deviceAuthorizationEndpoint() : The configurer for the OAuth2 Device Authorization endpoint. |
9 | deviceVerificationEndpoint() : The configurer for the OAuth2 Device Verification endpoint. |
10 | tokenEndpoint() : The configurer for the OAuth2 Token endpoint. |
11 | tokenIntrospectionEndpoint() : The configurer for the OAuth2 Token Introspection endpoint. |
12 | tokenRevocationEndpoint() : The configurer for the OAuth2 Token Revocation endpoint. |
13 | authorizationServerMetadataEndpoint() : The configurer for the OAuth2 Authorization Server Metadata endpoint. |
14 | providerConfigurationEndpoint() : The configurer for the OpenID Connect 1.0 Provider Configuration endpoint. |
15 | logoutEndpoint() : The configurer for the OpenID Connect 1.0 Logout endpoint. |
16 | userInfoEndpoint() : The configurer for the OpenID Connect 1.0 UserInfo endpoint. |
17 | clientRegistrationEndpoint() : The configurer for the OpenID Connect 1.0 Client Registration endpoint. |
Configuring Authorization Server Settings
AuthorizationServerSettings`包含OAuth2授权服务器的配置设置。它指定协议端点的`URI
,以及 issuer identifier.针对协议端点的默认`URI`如下所示:
AuthorizationServerSettings
contains the configuration settings for the OAuth2 authorization server.
It specifies the URI
for the protocol endpoints as well as the issuer identifier.
The default URI
for the protocol endpoints are as follows:
public final class AuthorizationServerSettings extends AbstractSettings {
...
public static Builder builder() {
return new Builder()
.authorizationEndpoint("/oauth2/authorize")
.deviceAuthorizationEndpoint("/oauth2/device_authorization")
.deviceVerificationEndpoint("/oauth2/device_verification")
.tokenEndpoint("/oauth2/token")
.tokenIntrospectionEndpoint("/oauth2/introspect")
.tokenRevocationEndpoint("/oauth2/revoke")
.jwkSetEndpoint("/oauth2/jwks")
.oidcLogoutEndpoint("/connect/logout")
.oidcUserInfoEndpoint("/userinfo")
.oidcClientRegistrationEndpoint("/connect/register");
}
...
}
|
|
如果尚未提供, |
|
以下示例演示如何自定义配置设置并注册一个 AuthorizationServerSettings
@Bean
:
The following example shows how to customize the configuration settings and register an AuthorizationServerSettings
@Bean
:
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder()
.issuer("https://example.com")
.authorizationEndpoint("/oauth2/v1/authorize")
.deviceAuthorizationEndpoint("/oauth2/v1/device_authorization")
.deviceVerificationEndpoint("/oauth2/v1/device_verification")
.tokenEndpoint("/oauth2/v1/token")
.tokenIntrospectionEndpoint("/oauth2/v1/introspect")
.tokenRevocationEndpoint("/oauth2/v1/revoke")
.jwkSetEndpoint("/oauth2/v1/jwks")
.oidcLogoutEndpoint("/connect/v1/logout")
.oidcUserInfoEndpoint("/connect/v1/userinfo")
.oidcClientRegistrationEndpoint("/connect/v1/register")
.build();
}
AuthorizationServerContext
是一个上下文对象,它保存授权服务器运行时环境的信息。可通过它访问 AuthorizationServerSettings
和“当前”颁发者标识符。
The AuthorizationServerContext
is a context object that holds information of the Authorization Server runtime environment.
It provides access to the AuthorizationServerSettings
and the “current” issuer identifier.
如果没有在 |
If the issuer identifier is not configured in |
|
The |
Configuring Client Authentication
`OAuth2ClientAuthenticationConfigurer`提供了自定义 OAuth2 client authentication的能力。它定义了让你能够自定义针对客户端认证请求进行预处理、主处理和后处理逻辑的扩展点。
OAuth2ClientAuthenticationConfigurer
provides the ability to customize OAuth2 client authentication.
It defines extension points that let you customize the pre-processing, main processing, and post-processing logic for client authentication requests.
OAuth2ClientAuthenticationConfigurer
提供以下配置选项:
OAuth2ClientAuthenticationConfigurer
provides the following configuration options:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer();
http.apply(authorizationServerConfigurer);
authorizationServerConfigurer
.clientAuthentication(clientAuthentication ->
clientAuthentication
.authenticationConverter(authenticationConverter) 1
.authenticationConverters(authenticationConvertersConsumer) 2
.authenticationProvider(authenticationProvider) 3
.authenticationProviders(authenticationProvidersConsumer) 4
.authenticationSuccessHandler(authenticationSuccessHandler) 5
.errorResponseHandler(errorResponseHandler) 6
);
return http.build();
}
1 | authenticationConverter() : Adds an AuthenticationConverter (pre-processor) used when attempting to extract client credentials from HttpServletRequest to an instance of OAuth2ClientAuthenticationToken . |
2 | authenticationConverters() : Sets the Consumer providing access to the List of default and (optionally) added AuthenticationConverter’s allowing the ability to add, remove, or customize a specific `AuthenticationConverter . |
3 | authenticationProvider() : Adds an AuthenticationProvider (main processor) used for authenticating the OAuth2ClientAuthenticationToken . |
4 | authenticationProviders() : Sets the Consumer providing access to the List of default and (optionally) added AuthenticationProvider’s allowing the ability to add, remove, or customize a specific `AuthenticationProvider . |
5 | authenticationSuccessHandler() : The AuthenticationSuccessHandler (post-processor) used for handling a successful client authentication and associating the OAuth2ClientAuthenticationToken to the SecurityContext . |
6 | errorResponseHandler() : The AuthenticationFailureHandler (post-processor) used for handling a failed client authentication and returning the OAuth2Error response. |
OAuth2ClientAuthenticationConfigurer
配置 OAuth2ClientAuthenticationFilter
并将其注册到 OAuth2 授权服务器 SecurityFilterChain
@Bean
。OAuth2ClientAuthenticationFilter
是处理客户端身份验证请求的 Filter
。
OAuth2ClientAuthenticationConfigurer
configures the OAuth2ClientAuthenticationFilter
and registers it with the OAuth2 authorization server SecurityFilterChain
@Bean
.
OAuth2ClientAuthenticationFilter
is the Filter
that processes client authentication requests.
在默认情况下,客户端验证对于 OAuth2 Token endpoint,OAuth2 Token Introspection endpoint和 OAuth2 Token Revocation endpoint 是必需的。所支持的客户端验证方法是 client_secret_basic
,client_secret_post
,private_key_jwt
,client_secret_jwt`和 `none
(公共客户端)。
By default, client authentication is required for the OAuth2 Token endpoint, the OAuth2 Token Introspection endpoint, and the OAuth2 Token Revocation endpoint.
The supported client authentication methods are client_secret_basic
, client_secret_post
, private_key_jwt
, client_secret_jwt
, and none
(public clients).
OAuth2ClientAuthenticationFilter
使用以下默认值配置:
OAuth2ClientAuthenticationFilter
is configured with the following defaults:
-
AuthenticationConverter
— ADelegatingAuthenticationConverter
composed ofJwtClientAssertionAuthenticationConverter
,ClientSecretBasicAuthenticationConverter
,ClientSecretPostAuthenticationConverter
, andPublicClientAuthenticationConverter
. -
AuthenticationManager
— AnAuthenticationManager
composed ofJwtClientAssertionAuthenticationProvider
,ClientSecretAuthenticationProvider
, andPublicClientAuthenticationProvider
. -
AuthenticationSuccessHandler
— An internal implementation that associates the “authenticated”OAuth2ClientAuthenticationToken
(currentAuthentication
) to theSecurityContext
. -
AuthenticationFailureHandler
— An internal implementation that uses theOAuth2Error
associated with theOAuth2AuthenticationException
to return the OAuth2 error response.
Customizing Jwt Client Assertion Validation
JwtClientAssertionDecoderFactory.DEFAULT_JWT_VALIDATOR_FACTORY
是为指定 RegisteredClient
提供 OAuth2TokenValidator<Jwt>
的默认工厂,用于验证 Jwt
客户端声明的 iss
、sub
、aud
、exp
和 nbf
声明。
JwtClientAssertionDecoderFactory.DEFAULT_JWT_VALIDATOR_FACTORY
is the default factory that provides an OAuth2TokenValidator<Jwt>
for the specified RegisteredClient
and is used for validating the iss
, sub
, aud
, exp
and nbf
claims of the Jwt
client assertion.
JwtClientAssertionDecoderFactory
提供了覆盖默认 Jwt
客户端声明验证的功能,方法是向 setJwtValidatorFactory()
提供一个类型为 Function<RegisteredClient, OAuth2TokenValidator<Jwt>>
的自定义工厂。
JwtClientAssertionDecoderFactory
provides the ability to override the default Jwt
client assertion validation by supplying a custom factory of type Function<RegisteredClient, OAuth2TokenValidator<Jwt>>
to setJwtValidatorFactory()
.
|
|
自定义 JwtClientAssertionDecoderFactory
的常见用例是在 Jwt
客户端声明中验证其他声明。
A common use case for customizing JwtClientAssertionDecoderFactory
is to validate additional claims in the Jwt
client assertion.
以下示例展示了如何使用一个自定义的 JwtClientAssertionDecoderFactory
来配置 JwtClientAssertionAuthenticationProvider
,该工厂会在 Jwt
客户端声明中验证其他声明:
The following example shows how to configure JwtClientAssertionAuthenticationProvider
with a customized JwtClientAssertionDecoderFactory
that validates an additional claim in the Jwt
client assertion:
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer();
http.apply(authorizationServerConfigurer);
authorizationServerConfigurer
.clientAuthentication(clientAuthentication ->
clientAuthentication
.authenticationProviders(configureJwtClientAssertionValidator())
);
return http.build();
}
private Consumer<List<AuthenticationProvider>> configureJwtClientAssertionValidator() {
return (authenticationProviders) ->
authenticationProviders.forEach((authenticationProvider) -> {
if (authenticationProvider instanceof JwtClientAssertionAuthenticationProvider) {
// Customize JwtClientAssertionDecoderFactory
JwtClientAssertionDecoderFactory jwtDecoderFactory = new JwtClientAssertionDecoderFactory();
Function<RegisteredClient, OAuth2TokenValidator<Jwt>> jwtValidatorFactory = (registeredClient) ->
new DelegatingOAuth2TokenValidator<>(
// Use default validators
JwtClientAssertionDecoderFactory.DEFAULT_JWT_VALIDATOR_FACTORY.apply(registeredClient),
// Add custom validator
new JwtClaimValidator<>("claim", "value"::equals));
jwtDecoderFactory.setJwtValidatorFactory(jwtValidatorFactory);
((JwtClientAssertionAuthenticationProvider) authenticationProvider)
.setJwtDecoderFactory(jwtDecoderFactory);
}
});
}