configuration-model.adoc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. [[configuration-model]]
  2. = Configuration Model
  3. [[default-configuration]]
  4. == Default configuration
  5. `OAuth2AuthorizationServerConfiguration` is a `@Configuration` that provides the minimal default configuration for an OAuth2 authorization server.
  6. `OAuth2AuthorizationServerConfiguration` uses xref:configuration-model.adoc#customizing-the-configuration[`OAuth2AuthorizationServerConfigurer`] to apply the default configuration and registers a `SecurityFilterChain` `@Bean` composed of all the infrastructure components supporting an OAuth2 authorization server.
  7. [TIP]
  8. `OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(HttpSecurity)` is a convenience (`static`) utility method that applies the default OAuth2 security configuration to `HttpSecurity`.
  9. The OAuth2 authorization server `SecurityFilterChain` `@Bean` is configured with the following default protocol endpoints:
  10. * xref:protocol-endpoints.adoc#oauth2-authorization-endpoint[OAuth2 Authorization endpoint]
  11. * xref:protocol-endpoints.adoc#oauth2-device-authorization-endpoint[OAuth2 Device Authorization Endpoint]
  12. * xref:protocol-endpoints.adoc#oauth2-device-verification-endpoint[OAuth2 Device Verification Endpoint]
  13. * xref:protocol-endpoints.adoc#oauth2-token-endpoint[OAuth2 Token endpoint]
  14. * xref:protocol-endpoints.adoc#oauth2-token-introspection-endpoint[OAuth2 Token Introspection endpoint]
  15. * xref:protocol-endpoints.adoc#oauth2-token-revocation-endpoint[OAuth2 Token Revocation endpoint]
  16. * xref:protocol-endpoints.adoc#oauth2-authorization-server-metadata-endpoint[OAuth2 Authorization Server Metadata endpoint]
  17. * xref:protocol-endpoints.adoc#jwk-set-endpoint[JWK Set endpoint]
  18. [NOTE]
  19. The JWK Set endpoint is configured *only* if a `JWKSource<SecurityContext>` `@Bean` is registered.
  20. The following example shows how to use `OAuth2AuthorizationServerConfiguration` to apply the minimal default configuration:
  21. [source,java]
  22. ----
  23. @Configuration
  24. @Import(OAuth2AuthorizationServerConfiguration.class)
  25. public class AuthorizationServerConfig {
  26. @Bean
  27. public RegisteredClientRepository registeredClientRepository() {
  28. List<RegisteredClient> registrations = ...
  29. return new InMemoryRegisteredClientRepository(registrations);
  30. }
  31. @Bean
  32. public JWKSource<SecurityContext> jwkSource() {
  33. RSAKey rsaKey = ...
  34. JWKSet jwkSet = new JWKSet(rsaKey);
  35. return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
  36. }
  37. }
  38. ----
  39. [IMPORTANT]
  40. The https://datatracker.ietf.org/doc/html/rfc6749#section-4.1[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.
  41. https://openid.net/specs/openid-connect-core-1_0.html[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`:
  42. [source,java]
  43. ----
  44. @Bean
  45. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
  46. OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
  47. http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
  48. .oidc(Customizer.withDefaults()); // Initialize `OidcConfigurer`
  49. return http.build();
  50. }
  51. ----
  52. In addition to the default protocol endpoints, the OAuth2 authorization server `SecurityFilterChain` `@Bean` is configured with the following OpenID Connect 1.0 protocol endpoints:
  53. * xref:protocol-endpoints.adoc#oidc-provider-configuration-endpoint[OpenID Connect 1.0 Provider Configuration endpoint]
  54. * xref:protocol-endpoints.adoc#oidc-logout-endpoint[OpenID Connect 1.0 Logout endpoint]
  55. * xref:protocol-endpoints.adoc#oidc-user-info-endpoint[OpenID Connect 1.0 UserInfo endpoint]
  56. [NOTE]
  57. The xref:protocol-endpoints.adoc#oidc-client-registration-endpoint[OpenID Connect 1.0 Client Registration endpoint] is disabled by default because many deployments do not require dynamic client registration.
  58. [TIP]
  59. `OAuth2AuthorizationServerConfiguration.jwtDecoder(JWKSource<SecurityContext>)` is a convenience (`static`) utility method that can be used to register a `JwtDecoder` `@Bean`, which is *REQUIRED* for the xref:protocol-endpoints.adoc#oidc-user-info-endpoint[OpenID Connect 1.0 UserInfo endpoint] and the xref:protocol-endpoints.adoc#oidc-client-registration-endpoint[OpenID Connect 1.0 Client Registration endpoint].
  60. The following example shows how to register a `JwtDecoder` `@Bean`:
  61. [source,java]
  62. ----
  63. @Bean
  64. public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
  65. return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
  66. }
  67. ----
  68. 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.
  69. [[customizing-the-configuration]]
  70. == Customizing the configuration
  71. `OAuth2AuthorizationServerConfigurer` provides the ability to fully customize the security configuration for an OAuth2 authorization server.
  72. It lets you specify the core components to use - for example, xref:core-model-components.adoc#registered-client-repository[`RegisteredClientRepository`], xref:core-model-components.adoc#oauth2-authorization-service[`OAuth2AuthorizationService`], xref:core-model-components.adoc#oauth2-token-generator[`OAuth2TokenGenerator`], and others.
  73. Furthermore, it lets you customize the request processing logic for the protocol endpoints – for example, xref:protocol-endpoints.adoc#oauth2-authorization-endpoint[authorization endpoint], xref:protocol-endpoints.adoc#oauth2-device-authorization-endpoint[device authorization endpoint], xref:protocol-endpoints.adoc#oauth2-device-verification-endpoint[device verification endpoint], xref:protocol-endpoints.adoc#oauth2-token-endpoint[token endpoint], xref:protocol-endpoints.adoc#oauth2-token-introspection-endpoint[token introspection endpoint], and others.
  74. `OAuth2AuthorizationServerConfigurer` provides the following configuration options:
  75. [source,java]
  76. ----
  77. @Bean
  78. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
  79. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
  80. new OAuth2AuthorizationServerConfigurer();
  81. http.apply(authorizationServerConfigurer);
  82. authorizationServerConfigurer
  83. .registeredClientRepository(registeredClientRepository) <1>
  84. .authorizationService(authorizationService) <2>
  85. .authorizationConsentService(authorizationConsentService) <3>
  86. .authorizationServerSettings(authorizationServerSettings) <4>
  87. .tokenGenerator(tokenGenerator) <5>
  88. .clientAuthentication(clientAuthentication -> { }) <6>
  89. .authorizationEndpoint(authorizationEndpoint -> { }) <7>
  90. .deviceAuthorizationEndpoint(deviceAuthorizationEndpoint -> { }) <8>
  91. .deviceVerificationEndpoint(deviceVerificationEndpoint -> { }) <9>
  92. .tokenEndpoint(tokenEndpoint -> { }) <10>
  93. .tokenIntrospectionEndpoint(tokenIntrospectionEndpoint -> { }) <11>
  94. .tokenRevocationEndpoint(tokenRevocationEndpoint -> { }) <12>
  95. .authorizationServerMetadataEndpoint(authorizationServerMetadataEndpoint -> { }) <13>
  96. .oidc(oidc -> oidc
  97. .providerConfigurationEndpoint(providerConfigurationEndpoint -> { }) <14>
  98. .logoutEndpoint(logoutEndpoint -> { }) <15>
  99. .userInfoEndpoint(userInfoEndpoint -> { }) <16>
  100. .clientRegistrationEndpoint(clientRegistrationEndpoint -> { }) <17>
  101. );
  102. return http.build();
  103. }
  104. ----
  105. <1> `registeredClientRepository()`: The xref:core-model-components.adoc#registered-client-repository[`RegisteredClientRepository`] (*REQUIRED*) for managing new and existing clients.
  106. <2> `authorizationService()`: The xref:core-model-components.adoc#oauth2-authorization-service[`OAuth2AuthorizationService`] for managing new and existing authorizations.
  107. <3> `authorizationConsentService()`: The xref:core-model-components.adoc#oauth2-authorization-consent-service[`OAuth2AuthorizationConsentService`] for managing new and existing authorization consents.
  108. <4> `authorizationServerSettings()`: The xref:configuration-model.adoc#configuring-authorization-server-settings[`AuthorizationServerSettings`] (*REQUIRED*) for customizing configuration settings for the OAuth2 authorization server.
  109. <5> `tokenGenerator()`: The xref:core-model-components.adoc#oauth2-token-generator[`OAuth2TokenGenerator`] for generating tokens supported by the OAuth2 authorization server.
  110. <6> `clientAuthentication()`: The configurer for xref:configuration-model.adoc#configuring-client-authentication[OAuth2 Client Authentication].
  111. <7> `authorizationEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-authorization-endpoint[OAuth2 Authorization endpoint].
  112. <8> `deviceAuthorizationEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-device-authorization-endpoint[OAuth2 Device Authorization endpoint].
  113. <9> `deviceVerificationEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-device-verification-endpoint[OAuth2 Device Verification endpoint].
  114. <10> `tokenEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-token-endpoint[OAuth2 Token endpoint].
  115. <11> `tokenIntrospectionEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-token-introspection-endpoint[OAuth2 Token Introspection endpoint].
  116. <12> `tokenRevocationEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-token-revocation-endpoint[OAuth2 Token Revocation endpoint].
  117. <13> `authorizationServerMetadataEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oauth2-authorization-server-metadata-endpoint[OAuth2 Authorization Server Metadata endpoint].
  118. <14> `providerConfigurationEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oidc-provider-configuration-endpoint[OpenID Connect 1.0 Provider Configuration endpoint].
  119. <15> `logoutEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oidc-logout-endpoint[OpenID Connect 1.0 Logout endpoint].
  120. <16> `userInfoEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oidc-user-info-endpoint[OpenID Connect 1.0 UserInfo endpoint].
  121. <17> `clientRegistrationEndpoint()`: The configurer for the xref:protocol-endpoints.adoc#oidc-client-registration-endpoint[OpenID Connect 1.0 Client Registration endpoint].
  122. [[configuring-authorization-server-settings]]
  123. == Configuring Authorization Server Settings
  124. `AuthorizationServerSettings` contains the configuration settings for the OAuth2 authorization server.
  125. It specifies the `URI` for the protocol endpoints as well as the https://datatracker.ietf.org/doc/html/rfc8414#section-2[issuer identifier].
  126. The default `URI` for the protocol endpoints are as follows:
  127. [source,java]
  128. ----
  129. public final class AuthorizationServerSettings extends AbstractSettings {
  130. ...
  131. public static Builder builder() {
  132. return new Builder()
  133. .authorizationEndpoint("/oauth2/authorize")
  134. .deviceAuthorizationEndpoint("/oauth2/device_authorization")
  135. .deviceVerificationEndpoint("/oauth2/device_verification")
  136. .tokenEndpoint("/oauth2/token")
  137. .tokenIntrospectionEndpoint("/oauth2/introspect")
  138. .tokenRevocationEndpoint("/oauth2/revoke")
  139. .jwkSetEndpoint("/oauth2/jwks")
  140. .oidcLogoutEndpoint("/connect/logout")
  141. .oidcUserInfoEndpoint("/userinfo")
  142. .oidcClientRegistrationEndpoint("/connect/register");
  143. }
  144. ...
  145. }
  146. ----
  147. [NOTE]
  148. `AuthorizationServerSettings` is a *REQUIRED* component.
  149. [TIP]
  150. xref:configuration-model.adoc#default-configuration[`@Import(OAuth2AuthorizationServerConfiguration.class)`] automatically registers an `AuthorizationServerSettings` `@Bean`, if not already provided.
  151. The following example shows how to customize the configuration settings and register an `AuthorizationServerSettings` `@Bean`:
  152. [source,java]
  153. ----
  154. @Bean
  155. public AuthorizationServerSettings authorizationServerSettings() {
  156. return AuthorizationServerSettings.builder()
  157. .issuer("https://example.com")
  158. .authorizationEndpoint("/oauth2/v1/authorize")
  159. .deviceAuthorizationEndpoint("/oauth2/v1/device_authorization")
  160. .deviceVerificationEndpoint("/oauth2/v1/device_verification")
  161. .tokenEndpoint("/oauth2/v1/token")
  162. .tokenIntrospectionEndpoint("/oauth2/v1/introspect")
  163. .tokenRevocationEndpoint("/oauth2/v1/revoke")
  164. .jwkSetEndpoint("/oauth2/v1/jwks")
  165. .oidcLogoutEndpoint("/connect/v1/logout")
  166. .oidcUserInfoEndpoint("/connect/v1/userinfo")
  167. .oidcClientRegistrationEndpoint("/connect/v1/register")
  168. .build();
  169. }
  170. ----
  171. The `AuthorizationServerContext` is a context object that holds information of the Authorization Server runtime environment.
  172. It provides access to the `AuthorizationServerSettings` and the "`current`" issuer identifier.
  173. [NOTE]
  174. If the issuer identifier is not configured in `AuthorizationServerSettings.builder().issuer(String)`, it is resolved from the current request.
  175. [NOTE]
  176. The `AuthorizationServerContext` is accessible through the `AuthorizationServerContextHolder`, which associates it with the current request thread by using a `ThreadLocal`.
  177. [[configuring-client-authentication]]
  178. == Configuring Client Authentication
  179. `OAuth2ClientAuthenticationConfigurer` provides the ability to customize https://datatracker.ietf.org/doc/html/rfc6749#section-2.3[OAuth2 client authentication].
  180. It defines extension points that let you customize the pre-processing, main processing, and post-processing logic for client authentication requests.
  181. `OAuth2ClientAuthenticationConfigurer` provides the following configuration options:
  182. [source,java]
  183. ----
  184. @Bean
  185. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
  186. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
  187. new OAuth2AuthorizationServerConfigurer();
  188. http.apply(authorizationServerConfigurer);
  189. authorizationServerConfigurer
  190. .clientAuthentication(clientAuthentication ->
  191. clientAuthentication
  192. .authenticationConverter(authenticationConverter) <1>
  193. .authenticationConverters(authenticationConvertersConsumer) <2>
  194. .authenticationProvider(authenticationProvider) <3>
  195. .authenticationProviders(authenticationProvidersConsumer) <4>
  196. .authenticationSuccessHandler(authenticationSuccessHandler) <5>
  197. .errorResponseHandler(errorResponseHandler) <6>
  198. );
  199. return http.build();
  200. }
  201. ----
  202. <1> `authenticationConverter()`: Adds an `AuthenticationConverter` (_pre-processor_) used when attempting to extract client credentials from `HttpServletRequest` to an instance of `OAuth2ClientAuthenticationToken`.
  203. <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`.
  204. <3> `authenticationProvider()`: Adds an `AuthenticationProvider` (_main processor_) used for authenticating the `OAuth2ClientAuthenticationToken`.
  205. <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`.
  206. <5> `authenticationSuccessHandler()`: The `AuthenticationSuccessHandler` (_post-processor_) used for handling a successful client authentication and associating the `OAuth2ClientAuthenticationToken` to the `SecurityContext`.
  207. <6> `errorResponseHandler()`: The `AuthenticationFailureHandler` (_post-processor_) used for handling a failed client authentication and returning the https://datatracker.ietf.org/doc/html/rfc6749#section-5.2[`OAuth2Error` response].
  208. `OAuth2ClientAuthenticationConfigurer` configures the `OAuth2ClientAuthenticationFilter` and registers it with the OAuth2 authorization server `SecurityFilterChain` `@Bean`.
  209. `OAuth2ClientAuthenticationFilter` is the `Filter` that processes client authentication requests.
  210. By default, client authentication is required for the xref:protocol-endpoints.adoc#oauth2-token-endpoint[OAuth2 Token endpoint], the xref:protocol-endpoints.adoc#oauth2-token-introspection-endpoint[OAuth2 Token Introspection endpoint], and the xref:protocol-endpoints.adoc#oauth2-token-revocation-endpoint[OAuth2 Token Revocation endpoint].
  211. The supported client authentication methods are `client_secret_basic`, `client_secret_post`, `private_key_jwt`, `client_secret_jwt`, and `none` (public clients).
  212. `OAuth2ClientAuthenticationFilter` is configured with the following defaults:
  213. * `*AuthenticationConverter*` -- A `DelegatingAuthenticationConverter` composed of `JwtClientAssertionAuthenticationConverter`, `ClientSecretBasicAuthenticationConverter`, `ClientSecretPostAuthenticationConverter`, and `PublicClientAuthenticationConverter`.
  214. * `*AuthenticationManager*` -- An `AuthenticationManager` composed of `JwtClientAssertionAuthenticationProvider`, `ClientSecretAuthenticationProvider`, and `PublicClientAuthenticationProvider`.
  215. * `*AuthenticationSuccessHandler*` -- An internal implementation that associates the "`authenticated`" `OAuth2ClientAuthenticationToken` (current `Authentication`) to the `SecurityContext`.
  216. * `*AuthenticationFailureHandler*` -- An internal implementation that uses the `OAuth2Error` associated with the `OAuth2AuthenticationException` to return the OAuth2 error response.
  217. [[configuring-client-authentication-customizing-jwt-client-assertion-validation]]
  218. === Customizing Jwt Client Assertion Validation
  219. `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.
  220. `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()`.
  221. [NOTE]
  222. `JwtClientAssertionDecoderFactory` is the default `JwtDecoderFactory` used by `JwtClientAssertionAuthenticationProvider` that provides a `JwtDecoder` for the specified `RegisteredClient` and is used for authenticating a `Jwt` Bearer Token during OAuth2 client authentication.
  223. A common use case for customizing `JwtClientAssertionDecoderFactory` is to validate additional claims in the `Jwt` client assertion.
  224. The following example shows how to configure `JwtClientAssertionAuthenticationProvider` with a customized `JwtClientAssertionDecoderFactory` that validates an additional claim in the `Jwt` client assertion:
  225. [source,java]
  226. ----
  227. @Bean
  228. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
  229. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
  230. new OAuth2AuthorizationServerConfigurer();
  231. http.apply(authorizationServerConfigurer);
  232. authorizationServerConfigurer
  233. .clientAuthentication(clientAuthentication ->
  234. clientAuthentication
  235. .authenticationProviders(configureJwtClientAssertionValidator())
  236. );
  237. return http.build();
  238. }
  239. private Consumer<List<AuthenticationProvider>> configureJwtClientAssertionValidator() {
  240. return (authenticationProviders) ->
  241. authenticationProviders.forEach((authenticationProvider) -> {
  242. if (authenticationProvider instanceof JwtClientAssertionAuthenticationProvider) {
  243. // Customize JwtClientAssertionDecoderFactory
  244. JwtClientAssertionDecoderFactory jwtDecoderFactory = new JwtClientAssertionDecoderFactory();
  245. Function<RegisteredClient, OAuth2TokenValidator<Jwt>> jwtValidatorFactory = (registeredClient) ->
  246. new DelegatingOAuth2TokenValidator<>(
  247. // Use default validators
  248. JwtClientAssertionDecoderFactory.DEFAULT_JWT_VALIDATOR_FACTORY.apply(registeredClient),
  249. // Add custom validator
  250. new JwtClaimValidator<>("claim", "value"::equals));
  251. jwtDecoderFactory.setJwtValidatorFactory(jwtValidatorFactory);
  252. ((JwtClientAssertionAuthenticationProvider) authenticationProvider)
  253. .setJwtDecoderFactory(jwtDecoderFactory);
  254. }
  255. });
  256. }
  257. ----