diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index c6f8d0e8fb..f2b3204070 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -56,7 +56,11 @@ *** xref:servlet/authorization/acls.adoc[Domain Object Security ACLs] ** xref:servlet/oauth2/index.adoc[OAuth2] *** xref:servlet/oauth2/oauth2-login.adoc[OAuth2 Log In] -*** xref:servlet/oauth2/oauth2-client.adoc[OAuth2 Client] +*** xref:servlet/oauth2/client/index.adoc[OAuth2 Client] +**** xref:servlet/oauth2/client/core.adoc[Core Interfaces and Classes] +**** xref:servlet/oauth2/client/authorization-grants.adoc[OAuth2 Authorization Grants] +**** xref:servlet/oauth2/client/client-authentication.adoc[OAuth2 Client Authentication] +**** xref:servlet/oauth2/client/authorized-clients.adoc[OAuth2 Authorized Clients] *** xref:servlet/oauth2/resource-server/index.adoc[OAuth2 Resource Server] **** xref:servlet/oauth2/resource-server/jwt.adoc[JWT] **** xref:servlet/oauth2/resource-server/opaque-token.adoc[Opaque Token] diff --git a/docs/modules/ROOT/pages/features/integrations/jackson.adoc b/docs/modules/ROOT/pages/features/integrations/jackson.adoc index e1c407763b..1f67bf98a2 100644 --- a/docs/modules/ROOT/pages/features/integrations/jackson.adoc +++ b/docs/modules/ROOT/pages/features/integrations/jackson.adoc @@ -42,6 +42,6 @@ The following Spring Security modules provide Jackson support: - spring-security-core (`CoreJackson2Module`) - spring-security-web (`WebJackson2Module`, `WebServletJackson2Module`, `WebServerJackson2Module`) -- xref:servlet/oauth2/oauth2-client.adoc#oauth2client[ spring-security-oauth2-client] (`OAuth2ClientJackson2Module`) +- xref:servlet/oauth2/client/index.adoc#oauth2client[ spring-security-oauth2-client] (`OAuth2ClientJackson2Module`) - spring-security-cas (`CasJackson2Module`) ==== diff --git a/docs/modules/ROOT/pages/reactive/oauth2/login.adoc b/docs/modules/ROOT/pages/reactive/oauth2/login.adoc index a16160c0ff..4aee887bb3 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/login.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/login.adoc @@ -39,11 +39,11 @@ The redirect URI is the path in the application that the end-user's user-agent i In the "Set a redirect URI" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. TIP: The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. -The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration]. +The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/client/core.adoc#oauth2Client-client-registration[ClientRegistration]. For our example, the `registrationId` is `google`. IMPORTANT: If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. -Also, see the supported xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. +Also, see the supported xref:servlet/oauth2/client/authorization-grants.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. [[webflux-oauth2-login-sample-config]] === Configure `application.yml` @@ -68,7 +68,7 @@ spring: .OAuth Client properties ==== <1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. -<2> Following the base property prefix is the ID for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration], such as google. +<2> Following the base property prefix is the ID for the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[`ClientRegistration`], such as google. ==== . Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. diff --git a/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc b/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc index f6cf413b68..17cd707fe1 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/database-schema.adoc @@ -367,7 +367,7 @@ END; [[dbschema-oauth2-client]] == OAuth 2.0 Client Schema -The JDBC implementation of xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-authorized-repo-service[ OAuth2AuthorizedClientService] (`JdbcOAuth2AuthorizedClientService`) requires a table for persisting `OAuth2AuthorizedClient`(s). +The JDBC implementation of xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-repo-service[ OAuth2AuthorizedClientService] (`JdbcOAuth2AuthorizedClientService`) requires a table for persisting `OAuth2AuthorizedClient`(s). You will need to adjust this schema to match the database dialect you are using. [source,ddl] diff --git a/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc b/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc index de5e3c6d26..0c23fe39f1 100644 --- a/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc +++ b/docs/modules/ROOT/pages/servlet/appendix/namespace/http.adoc @@ -947,7 +947,7 @@ Reference to the `JwtDecoderFactory` used by `OidcAuthorizationCodeAuthenticatio [[nsa-oauth2-client]] == -Configures xref:servlet/oauth2/oauth2-client.adoc#oauth2client[OAuth 2.0 Client] support. +Configures xref:servlet/oauth2/client/index.adoc#oauth2client[OAuth 2.0 Client] support. [[nsa-oauth2-client-parents]] @@ -982,7 +982,7 @@ Reference to the `OAuth2AuthorizedClientService`. [[nsa-authorization-code-grant]] == -Configures xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-grant-support[OAuth 2.0 Authorization Code Grant]. +Configures xref:servlet/oauth2/client/authorization-grants.adoc#oauth2Client-auth-grant-support[OAuth 2.0 Authorization Code Grant]. [[nsa-authorization-code-grant-parents]] @@ -1012,7 +1012,7 @@ Reference to the `OAuth2AccessTokenResponseClient`. [[nsa-client-registrations]] == -A container element for client(s) registered (xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration]) with an OAuth 2.0 or OpenID Connect 1.0 Provider. +A container element for client(s) registered (xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[ClientRegistration]) with an OAuth 2.0 or OpenID Connect 1.0 Provider. [[nsa-client-registrations-children]] diff --git a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/authorization-grants.adoc similarity index 53% rename from docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc rename to docs/modules/ROOT/pages/servlet/oauth2/client/authorization-grants.adoc index fa0c20eac4..b2a60ba35b 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-client.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/authorization-grants.adoc @@ -1,630 +1,21 @@ -[[oauth2client]] -= OAuth 2.0 Client - -The OAuth 2.0 Client features provide support for the Client role as defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework]. - -At a high-level, the core features available are: - -.Authorization Grant support -* https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] -* https://tools.ietf.org/html/rfc6749#section-6[Refresh Token] -* https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] -* https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] -* https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[JWT Bearer] - -.Client Authentication support -* https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] - -.HTTP Client support -* <> (for requesting protected resources) - -The `HttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. -In addition, `HttpSecurity.oauth2Client().authorizationCodeGrant()` enables the customization of the Authorization Code grant. - -The following code shows the complete configuration options provided by the `HttpSecurity.oauth2Client()` DSL: - -.OAuth2 Client Configuration Options -==== -.Java -[source,java,role="primary"] ----- -@EnableWebSecurity -public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .oauth2Client(oauth2 -> oauth2 - .clientRegistrationRepository(this.clientRegistrationRepository()) - .authorizedClientRepository(this.authorizedClientRepository()) - .authorizedClientService(this.authorizedClientService()) - .authorizationCodeGrant(codeGrant -> codeGrant - .authorizationRequestRepository(this.authorizationRequestRepository()) - .authorizationRequestResolver(this.authorizationRequestResolver()) - .accessTokenResponseClient(this.accessTokenResponseClient()) - ) - ); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@EnableWebSecurity -class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { - - override fun configure(http: HttpSecurity) { - http { - oauth2Client { - clientRegistrationRepository = clientRegistrationRepository() - authorizedClientRepository = authorizedClientRepository() - authorizedClientService = authorizedClientService() - authorizationCodeGrant { - authorizationRequestRepository = authorizationRequestRepository() - authorizationRequestResolver = authorizationRequestResolver() - accessTokenResponseClient = accessTokenResponseClient() - } - } - } - } -} ----- -==== - -In addition to the `HttpSecurity.oauth2Client()` DSL, XML configuration is also supported. - -The following code shows the complete configuration options available in the xref:servlet/appendix/namespace/http.adoc#nsa-oauth2-client[ security namespace]: - -.OAuth2 Client XML Configuration Options -==== -[source,xml] ----- - - - - - ----- -==== - -The `OAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `OAuth2AuthorizedClientProvider`(s). - -The following code shows an example of how to register an `OAuth2AuthorizedClientManager` `@Bean` and associate it with an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider: OAuth2AuthorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -The following sections will go into more detail on the core components used by OAuth 2.0 Client and the configuration options available: - -* <> -** <> -** <> -** <> -** <> -** <> -* <> -** <> -** <> -** <> -** <> -** <> -* <> -** <> -* <> -** <> -* <> - - -[[oauth2Client-core-interface-class]] -== Core Interfaces / Classes - - -[[oauth2Client-client-registration]] -=== ClientRegistration - -`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. - -A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. - -`ClientRegistration` and its properties are defined as follows: - -[source,java] ----- -public final class ClientRegistration { - private String registrationId; <1> - private String clientId; <2> - private String clientSecret; <3> - private ClientAuthenticationMethod clientAuthenticationMethod; <4> - private AuthorizationGrantType authorizationGrantType; <5> - private String redirectUri; <6> - private Set scopes; <7> - private ProviderDetails providerDetails; - private String clientName; <8> - - public class ProviderDetails { - private String authorizationUri; <9> - private String tokenUri; <10> - private UserInfoEndpoint userInfoEndpoint; - private String jwkSetUri; <11> - private String issuerUri; <12> - private Map configurationMetadata; <13> - - public class UserInfoEndpoint { - private String uri; <14> - private AuthenticationMethod authenticationMethod; <15> - private String userNameAttributeName; <16> - - } - } -} ----- -<1> `registrationId`: The ID that uniquely identifies the `ClientRegistration`. -<2> `clientId`: The client identifier. -<3> `clientSecret`: The client secret. -<4> `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider. -The supported values are *client_secret_basic*, *client_secret_post*, *private_key_jwt*, *client_secret_jwt* and *none* https://tools.ietf.org/html/rfc6749#section-2.1[(public clients)]. -<5> `authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four https://tools.ietf.org/html/rfc6749#section-1.3[Authorization Grant] types. - The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. -<6> `redirectUri`: The client's registered redirect URI that the _Authorization Server_ redirects the end-user's user-agent - to after the end-user has authenticated and authorized access to the client. -<7> `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. -<8> `clientName`: A descriptive name used for the client. -The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. -<9> `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. -<10> `tokenUri`: The Token Endpoint URI for the Authorization Server. -<11> `jwkSetUri`: The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] Set from the Authorization Server, - which contains the cryptographic key(s) used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the ID Token and optionally the UserInfo Response. -<12> `issuerUri`: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. -<13> `configurationMetadata`: The https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration Information]. - This information will only be available if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. -<14> `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. -<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint. -The supported values are *header*, *form* and *query*. -<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. - -A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. - -`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example: - -==== -.Java -[source,java,role="primary"] ----- -ClientRegistration clientRegistration = - ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() ----- -==== - -The above code will query in series `https://idp.example.com/issuer/.well-known/openid-configuration`, and then `https://idp.example.com/.well-known/openid-configuration/issuer`, and finally `https://idp.example.com/.well-known/oauth-authorization-server/issuer`, stopping at the first to return a 200 response. - -As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to only query the OpenID Connect Provider's Configuration endpoint. - -[[oauth2Client-client-registration-repo]] -=== ClientRegistrationRepository - -The `ClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). - -[NOTE] -Client registration information is ultimately stored and owned by the associated Authorization Server. -This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server. - -Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration._[registrationId]_` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ClientRegistrationRepository`. - -[NOTE] -The default implementation of `ClientRegistrationRepository` is `InMemoryClientRegistrationRepository`. - -The auto-configuration also registers the `ClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency-injection, if needed by the application. - -The following listing shows an example: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private ClientRegistrationRepository clientRegistrationRepository; - - @GetMapping("/") - public String index() { - ClientRegistration oktaRegistration = - this.clientRegistrationRepository.findByRegistrationId("okta"); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - - @Autowired - private lateinit var clientRegistrationRepository: ClientRegistrationRepository - - @GetMapping("/") - fun index(): String { - val oktaRegistration = - this.clientRegistrationRepository.findByRegistrationId("okta") - - //... - - return "index"; - } -} ----- -==== - -[[oauth2Client-authorized-client]] -=== OAuth2AuthorizedClient - -`OAuth2AuthorizedClient` is a representation of an Authorized Client. -A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources. - -`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. - - -[[oauth2Client-authorized-repo-service]] -=== OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService - -`OAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests. -Whereas, the primary role of `OAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. - -From a developer perspective, the `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` provides the capability to lookup an `OAuth2AccessToken` associated with a client so that it may be used to initiate a protected resource request. - -The following listing shows an example: - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @Autowired - private OAuth2AuthorizedClientService authorizedClientService; - - @GetMapping("/") - public String index(Authentication authentication) { - OAuth2AuthorizedClient authorizedClient = - this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); - - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - - @Autowired - private lateinit var authorizedClientService: OAuth2AuthorizedClientService - - @GetMapping("/") - fun index(authentication: Authentication): String { - val authorizedClient: OAuth2AuthorizedClient = - this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); - val accessToken = authorizedClient.accessToken - - ... - - return "index"; - } -} ----- -==== - -[NOTE] -Spring Boot 2.x auto-configuration registers an `OAuth2AuthorizedClientRepository` and/or `OAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`. -However, the application may choose to override and register a custom `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` `@Bean`. - -The default implementation of `OAuth2AuthorizedClientService` is `InMemoryOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient`(s) in-memory. - -Alternatively, the JDBC implementation `JdbcOAuth2AuthorizedClientService` may be configured for persisting `OAuth2AuthorizedClient`(s) in a database. - -[NOTE] -`JdbcOAuth2AuthorizedClientService` depends on the table definition described in xref:servlet/appendix/database-schema.adoc#dbschema-oauth2-client[ OAuth 2.0 Client Schema]. - - -[[oauth2Client-authorized-manager-provider]] -=== OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider - -The `OAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). - -The primary responsibilities include: - -* Authorizing (or re-authorizing) an OAuth 2.0 Client, using an `OAuth2AuthorizedClientProvider`. -* Delegating the persistence of an `OAuth2AuthorizedClient`, typically using an `OAuth2AuthorizedClientService` or `OAuth2AuthorizedClientRepository`. -* Delegating to an `OAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). -* Delegating to an `OAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). - -An `OAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. -Implementations will typically implement an authorization grant type, eg. `authorization_code`, `client_credentials`, etc. - -The default implementation of `OAuth2AuthorizedClientManager` is `DefaultOAuth2AuthorizedClientManager`, which is associated with an `OAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. -The `OAuth2AuthorizedClientProviderBuilder` may be used to configure and build the delegation-based composite. - -The following code shows an example of how to configure and build an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build(); - - DefaultOAuth2AuthorizedClientManager authorizedClientManager = - new DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .authorizationCode() - .refreshToken() - .clientCredentials() - .password() - .build() - val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientRepository) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - -When an authorization attempt succeeds, the `DefaultOAuth2AuthorizedClientManager` will delegate to the `OAuth2AuthorizationSuccessHandler`, which (by default) will save the `OAuth2AuthorizedClient` via the `OAuth2AuthorizedClientRepository`. -In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved `OAuth2AuthorizedClient` will be removed from the `OAuth2AuthorizedClientRepository` via the `RemoveAuthorizedClientOAuth2AuthorizationFailureHandler`. -The default behaviour may be customized via `setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)`. - -The `DefaultOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. -This can be useful when you need to supply an `OAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordOAuth2AuthorizedClientProvider` requires the resource owner's `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. - -The following code shows an example of the `contextAttributesMapper`: - -==== -.Java -[source,java,role="primary"] ----- -@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> contextAttributesMapper() { - return authorizeRequest -> { - Map 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; - }; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@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> { - return Function { authorizeRequest -> - var contextAttributes: MutableMap = mutableMapOf() - val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name) - val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME) - val password: String = 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 - } -} ----- -==== - -The `DefaultOAuth2AuthorizedClientManager` is designed to be used *_within_* the context of a `HttpServletRequest`. -When operating *_outside_* of a `HttpServletRequest` context, use `AuthorizedClientServiceOAuth2AuthorizedClientManager` instead. - -A _service application_ is a common use case for when to use an `AuthorizedClientServiceOAuth2AuthorizedClientManager`. -Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. -An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. - -The following code shows an example of how to configure an `AuthorizedClientServiceOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -public OAuth2AuthorizedClientManager authorizedClientManager( - ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientService authorizedClientService) { - - OAuth2AuthorizedClientProvider authorizedClientProvider = - OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build(); - - AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = - new AuthorizedClientServiceOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService); - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); - - return authorizedClientManager; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun authorizedClientManager( - clientRegistrationRepository: ClientRegistrationRepository, - authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager { - val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() - .clientCredentials() - .build() - val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService) - authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) - return authorizedClientManager -} ----- -==== - - [[oauth2Client-auth-grant-support]] -== Authorization Grant Support += Authorization Grant Support [[oauth2Client-auth-code-grant]] -=== Authorization Code +== Authorization Code [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant. -==== Obtaining Authorization +=== Obtaining Authorization [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant. -==== Initiating the Authorization Request +=== Initiating the Authorization Request The `OAuth2AuthorizationRequestRedirectFilter` uses an `OAuth2AuthorizationRequestResolver` to resolve an `OAuth2AuthorizationRequest` and initiate the Authorization Code grant flow by redirecting the end-user's user-agent to the Authorization Server's Authorization Endpoint. @@ -705,7 +96,7 @@ spring: Configuring the `redirect-uri` with `URI` template variables is especially useful when the OAuth 2.0 Client is running behind a xref:features/exploits/http.adoc#http-proxy-server[Proxy Server]. This ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`. -==== Customizing the Authorization Request +=== Customizing the Authorization Request One of the primary use cases an `OAuth2AuthorizationRequestResolver` can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework. @@ -852,7 +243,7 @@ private fun authorizationRequestCustomizer(): Consumer>`. The default implementation `OAuth2AuthorizationCodeGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.1.3[OAuth 2.0 Access Token Request]. @@ -937,7 +328,7 @@ If you prefer to only add additional parameters, you can provide `OAuth2Authoriz IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultAuthorizationCodeTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. The default `RestOperations` is configured as follows: @@ -1026,13 +417,13 @@ class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { [[oauth2Client-refresh-token-grant]] -=== Refresh Token +== Refresh Token [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token]. -==== Refreshing an Access Token +=== Refreshing an Access Token [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant. @@ -1042,7 +433,7 @@ The default implementation of `OAuth2AccessTokenResponseClient` for the Refresh The `DefaultRefreshTokenTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `DefaultRefreshTokenTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. The default implementation `OAuth2RefreshTokenGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-6[OAuth 2.0 Access Token Request]. @@ -1056,7 +447,7 @@ If you prefer to only add additional parameters, you can provide `OAuth2RefreshT IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultRefreshTokenTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. The default `RestOperations` is configured as follows: @@ -1137,13 +528,13 @@ If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2Au [[oauth2Client-client-creds-grant]] -=== Client Credentials +== Client Credentials [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant. -==== Requesting an Access Token +=== Requesting an Access Token [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-4.4.2[Access Token Request/Response] protocol flow for the Client Credentials grant. @@ -1153,7 +544,7 @@ The default implementation of `OAuth2AccessTokenResponseClient` for the Client C The `DefaultClientCredentialsTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `DefaultClientCredentialsTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. The default implementation `OAuth2ClientCredentialsGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.4.2[OAuth 2.0 Access Token Request]. @@ -1167,7 +558,7 @@ If you prefer to only add additional parameters, you can provide `OAuth2ClientCr IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultClientCredentialsTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. The default `RestOperations` is configured as follows: @@ -1241,7 +632,7 @@ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) `OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsOAuth2AuthorizedClientProvider`, which is an implementation of an `OAuth2AuthorizedClientProvider` for the Client Credentials grant. -==== Using the Access Token +=== Using the Access Token Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: @@ -1376,13 +767,13 @@ If not provided, it will default to `ServletRequestAttributes` using `RequestCon [[oauth2Client-password-grant]] -=== Resource Owner Password Credentials +== Resource Owner Password Credentials [NOTE] Please refer to the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] grant. -==== Requesting an Access Token +=== Requesting an Access Token [NOTE] Please refer to the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant. @@ -1392,7 +783,7 @@ The default implementation of `OAuth2AccessTokenResponseClient` for the Resource The `DefaultPasswordTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `DefaultPasswordTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. The default implementation `OAuth2PasswordGrantRequestEntityConverter` builds a `RequestEntity` representation of a standard https://tools.ietf.org/html/rfc6749#section-4.3.2[OAuth 2.0 Access Token Request]. @@ -1406,7 +797,7 @@ If you prefer to only add additional parameters, you can provide `OAuth2Password IMPORTANT: The custom `Converter` must return a valid `RequestEntity` representation of an OAuth 2.0 Access Token Request that is understood by the intended OAuth 2.0 Provider. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultPasswordTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. The default `RestOperations` is configured as follows: @@ -1481,7 +872,7 @@ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) `OAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordOAuth2AuthorizedClientProvider`, which is an implementation of an `OAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant. -==== Using the Access Token +=== Using the Access Token Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: @@ -1659,13 +1050,13 @@ If not provided, it will default to `ServletRequestAttributes` using `RequestCon [[oauth2Client-jwt-bearer-grant]] -=== JWT Bearer +== JWT Bearer [NOTE] Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on the https://datatracker.ietf.org/doc/html/rfc7523[JWT Bearer] grant. -==== Requesting an Access Token +=== Requesting an Access Token [NOTE] Please refer to the https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[Access Token Request/Response] protocol flow for the JWT Bearer grant. @@ -1675,7 +1066,7 @@ The default implementation of `OAuth2AccessTokenResponseClient` for the JWT Bear The `DefaultJwtBearerTokenResponseClient` is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response. -==== Customizing the Access Token Request +=== Customizing the Access Token Request If you need to customize the pre-processing of the Token Request, you can provide `DefaultJwtBearerTokenResponseClient.setRequestEntityConverter()` with a custom `Converter>`. The default implementation `JwtBearerGrantRequestEntityConverter` builds a `RequestEntity` representation of a https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[OAuth 2.0 Access Token Request]. @@ -1687,7 +1078,7 @@ To customize only the parameters of the request, you can provide `JwtBearerGrant If you prefer to only add additional parameters, you can provide `JwtBearerGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter>` which constructs an aggregate `Converter`. -==== Customizing the Access Token Response +=== Customizing the Access Token Response On the other end, if you need to customize the post-handling of the Token Response, you will need to provide `DefaultJwtBearerTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`. The default `RestOperations` is configured as follows: @@ -1763,7 +1154,7 @@ authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) ---- ==== -==== Using the Access Token +=== Using the Access Token Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: @@ -1879,491 +1270,3 @@ class OAuth2ResourceServerController { } ---- ==== - - -[[oauth2Client-client-auth-support]] -== Client Authentication Support - - -[[oauth2Client-jwt-bearer-auth]] -=== JWT Bearer - -[NOTE] -Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] Client Authentication. - -The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, -which is a `Converter` that customizes the Token Request parameters by adding -a signed JSON Web Token (JWS) in the `client_assertion` parameter. - -The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS -is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. - - -==== Authenticate using `private_key_jwt` - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-authentication-method: private_key_jwt - authorization-grant-type: authorization_code - ... ----- - -The following example shows how to configure `DefaultAuthorizationCodeTokenResponseClient`: - -==== -.Java -[source,java,role="primary"] ----- -Function jwkResolver = (clientRegistration) -> { - if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { - // Assuming RSA key type - RSAPublicKey publicKey = ... - RSAPrivateKey privateKey = ... - return new RSAKey.Builder(publicKey) - .privateKey(privateKey) - .keyID(UUID.randomUUID().toString()) - .build(); - } - return null; -}; - -OAuth2AuthorizationCodeGrantRequestEntityConverter requestEntityConverter = - new OAuth2AuthorizationCodeGrantRequestEntityConverter(); -requestEntityConverter.addParametersConverter( - new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); - -DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = - new DefaultAuthorizationCodeTokenResponseClient(); -tokenResponseClient.setRequestEntityConverter(requestEntityConverter); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val jwkResolver: Function = - Function { clientRegistration -> - if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { - // Assuming RSA key type - var publicKey: RSAPublicKey - var privateKey: RSAPrivateKey - RSAKey.Builder(publicKey) = //... - .privateKey(privateKey) = //... - .keyID(UUID.randomUUID().toString()) - .build() - } - null - } - -val requestEntityConverter = OAuth2AuthorizationCodeGrantRequestEntityConverter() -requestEntityConverter.addParametersConverter( - NimbusJwtClientAuthenticationParametersConverter(jwkResolver) -) - -val tokenResponseClient = DefaultAuthorizationCodeTokenResponseClient() -tokenResponseClient.setRequestEntityConverter(requestEntityConverter) ----- -==== - - -==== Authenticate using `client_secret_jwt` - -Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: - -[source,yaml] ----- -spring: - security: - oauth2: - client: - registration: - okta: - client-id: okta-client-id - client-secret: okta-client-secret - client-authentication-method: client_secret_jwt - authorization-grant-type: client_credentials - ... ----- - -The following example shows how to configure `DefaultClientCredentialsTokenResponseClient`: - -==== -.Java -[source,java,role="primary"] ----- -Function jwkResolver = (clientRegistration) -> { - if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { - SecretKeySpec secretKey = new SecretKeySpec( - clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), - "HmacSHA256"); - return new OctetSequenceKey.Builder(secretKey) - .keyID(UUID.randomUUID().toString()) - .build(); - } - return null; -}; - -OAuth2ClientCredentialsGrantRequestEntityConverter requestEntityConverter = - new OAuth2ClientCredentialsGrantRequestEntityConverter(); -requestEntityConverter.addParametersConverter( - new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); - -DefaultClientCredentialsTokenResponseClient tokenResponseClient = - new DefaultClientCredentialsTokenResponseClient(); -tokenResponseClient.setRequestEntityConverter(requestEntityConverter); ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -val jwkResolver = Function { clientRegistration: ClientRegistration -> - if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { - val secretKey = SecretKeySpec( - clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), - "HmacSHA256" - ) - OctetSequenceKey.Builder(secretKey) - .keyID(UUID.randomUUID().toString()) - .build() - } - null -} - -val requestEntityConverter = OAuth2ClientCredentialsGrantRequestEntityConverter() -requestEntityConverter.addParametersConverter( - NimbusJwtClientAuthenticationParametersConverter(jwkResolver) -) - -val tokenResponseClient = DefaultClientCredentialsTokenResponseClient() -tokenResponseClient.setRequestEntityConverter(requestEntityConverter) ----- -==== - - -[[oauth2Client-additional-features]] -== Additional Features - - -[[oauth2Client-registered-authorized-client]] -=== Resolving an Authorized Client - -The `@RegisteredOAuth2AuthorizedClient` annotation provides the capability of resolving a method parameter to an argument value of type `OAuth2AuthorizedClient`. -This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` using the `OAuth2AuthorizedClientManager` or `OAuth2AuthorizedClientService`. - -==== -.Java -[source,java,role="primary"] ----- -@Controller -public class OAuth2ClientController { - - @GetMapping("/") - public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { - OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); - - ... - - return "index"; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Controller -class OAuth2ClientController { - @GetMapping("/") - fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { - val accessToken = authorizedClient.accessToken - - ... - - return "index" - } -} ----- -==== - -The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses an <> and therefore inherits it's capabilities. - - -[[oauth2Client-webclient-servlet]] -== WebClient integration for Servlet Environments - -The OAuth 2.0 Client support integrates with `WebClient` using an `ExchangeFilterFunction`. - -The `ServletOAuth2AuthorizedClientExchangeFilterFunction` provides a simple mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. -It directly uses an <> and therefore inherits the following capabilities: - -* An `OAuth2AccessToken` will be requested if the client has not yet been authorized. -** `authorization_code` - triggers the Authorization Request redirect to initiate the flow -** `client_credentials` - the access token is obtained directly from the Token Endpoint -** `password` - the access token is obtained directly from the Token Endpoint -* If the `OAuth2AccessToken` is expired, it will be refreshed (or renewed) if an `OAuth2AuthorizedClientProvider` is available to perform the authorization - -The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { - val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build() -} ----- -==== - -=== Providing the Authorized Client - -The `ServletOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). - -The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { - String resourceUri = ... - - String body = webClient - .get() - .uri(resourceUri) - .attributes(oauth2AuthorizedClient(authorizedClient)) <1> - .retrieve() - .bodyToMono(String.class) - .block(); - - ... - - return "index"; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { - val resourceUri: String = ... - val body: String = webClient - .get() - .uri(resourceUri) - .attributes(oauth2AuthorizedClient(authorizedClient)) <1> - .retrieve() - .bodyToMono() - .block() - - ... - - return "index" -} ----- -==== - -<1> `oauth2AuthorizedClient()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. - -The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public String index() { - String resourceUri = ... - - String body = webClient - .get() - .uri(resourceUri) - .attributes(clientRegistrationId("okta")) <1> - .retrieve() - .bodyToMono(String.class) - .block(); - - ... - - return "index"; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(): String { - val resourceUri: String = ... - - val body: String = webClient - .get() - .uri(resourceUri) - .attributes(clientRegistrationId("okta")) <1> - .retrieve() - .bodyToMono() - .block() - - ... - - return "index" -} ----- -==== -<1> `clientRegistrationId()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. - -The following code shows how to set an `Authentication` as a request attribute: - -==== -.Java -[source,java,role="primary"] ----- -@GetMapping("/") -public String index() { - String resourceUri = ... - - Authentication anonymousAuthentication = new AnonymousAuthenticationToken( - "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - String body = webClient - .get() - .uri(resourceUri) - .attributes(authentication(anonymousAuthentication)) <1> - .retrieve() - .bodyToMono(String.class) - .block(); - - ... - - return "index"; -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@GetMapping("/") -fun index(): String { - val resourceUri: String = ... - - val anonymousAuthentication: Authentication = AnonymousAuthenticationToken( - "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")) - val body: String = webClient - .get() - .uri(resourceUri) - .attributes(authentication(anonymousAuthentication)) <1> - .retrieve() - .bodyToMono() - .block() - - ... - - return "index" -} ----- -==== -<1> `authentication()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive an access token bound to the provided principal. - - -=== Defaulting the Authorized Client - -If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServletOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use depending on it's configuration. - -If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated using `HttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. - -The following code shows the specific configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - oauth2Client.setDefaultOAuth2AuthorizedClient(true); - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { - val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - oauth2Client.setDefaultOAuth2AuthorizedClient(true) - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build() -} ----- -==== - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive the access token. - -Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. - -The following code shows the specific configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Bean -WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { - ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = - new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); - oauth2Client.setDefaultClientRegistrationId("okta"); - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build(); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { - val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) - oauth2Client.setDefaultClientRegistrationId("okta") - return WebClient.builder() - .apply(oauth2Client.oauth2Configuration()) - .build() -} ----- -==== - -[WARNING] -It is recommended to be cautious with this feature since all HTTP requests will receive the access token. diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/authorized-clients.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/authorized-clients.adoc new file mode 100644 index 0000000000..16a626dd73 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/authorized-clients.adoc @@ -0,0 +1,264 @@ +[[oauth2Client-additional-features]] += Authorized Client Features + +[[oauth2Client-registered-authorized-client]] +== Resolving an Authorized Client + +The `@RegisteredOAuth2AuthorizedClient` annotation provides the capability of resolving a method parameter to an argument value of type `OAuth2AuthorizedClient`. +This is a convenient alternative compared to accessing the `OAuth2AuthorizedClient` using the `OAuth2AuthorizedClientManager` or `OAuth2AuthorizedClientService`. + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @GetMapping("/") + public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + @GetMapping("/") + fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { + val accessToken = authorizedClient.accessToken + + ... + + return "index" + } +} +---- +==== + +The `@RegisteredOAuth2AuthorizedClient` annotation is handled by `OAuth2AuthorizedClientArgumentResolver`, which directly uses an xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-manager-provider[`OAuth2AuthorizedClientManager`] and therefore inherits it's capabilities. + + +[[oauth2Client-webclient-servlet]] +== WebClient integration for Servlet Environments + +The OAuth 2.0 Client support integrates with `WebClient` using an `ExchangeFilterFunction`. + +The `ServletOAuth2AuthorizedClientExchangeFilterFunction` provides a simple mechanism for requesting protected resources by using an `OAuth2AuthorizedClient` and including the associated `OAuth2AccessToken` as a Bearer Token. +It directly uses an xref:servlet/oauth2/client/core.adoc#oauth2Client-authorized-manager-provider[`OAuth2AuthorizedClientManager`] and therefore inherits the following capabilities: + +* An `OAuth2AccessToken` will be requested if the client has not yet been authorized. +** `authorization_code` - triggers the Authorization Request redirect to initiate the flow +** `client_credentials` - the access token is obtained directly from the Token Endpoint +** `password` - the access token is obtained directly from the Token Endpoint +* If the `OAuth2AccessToken` is expired, it will be refreshed (or renewed) if an `OAuth2AuthorizedClientProvider` is available to perform the authorization + +The following code shows an example of how to configure `WebClient` with OAuth 2.0 Client support: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { + val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build() +} +---- +==== + +=== Providing the Authorized Client + +The `ServletOAuth2AuthorizedClientExchangeFilterFunction` determines the client to use (for a request) by resolving the `OAuth2AuthorizedClient` from the `ClientRequest.attributes()` (request attributes). + +The following code shows how to set an `OAuth2AuthorizedClient` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public String index(@RegisteredOAuth2AuthorizedClient("okta") OAuth2AuthorizedClient authorizedClient) { + String resourceUri = ... + + String body = webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) <1> + .retrieve() + .bodyToMono(String.class) + .block(); + + ... + + return "index"; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(@RegisteredOAuth2AuthorizedClient("okta") authorizedClient: OAuth2AuthorizedClient): String { + val resourceUri: String = ... + val body: String = webClient + .get() + .uri(resourceUri) + .attributes(oauth2AuthorizedClient(authorizedClient)) <1> + .retrieve() + .bodyToMono() + .block() + + ... + + return "index" +} +---- +==== + +<1> `oauth2AuthorizedClient()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. + +The following code shows how to set the `ClientRegistration.getRegistrationId()` as a request attribute: + +==== +.Java +[source,java,role="primary"] +---- +@GetMapping("/") +public String index() { + String resourceUri = ... + + String body = webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) <1> + .retrieve() + .bodyToMono(String.class) + .block(); + + ... + + return "index"; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@GetMapping("/") +fun index(): String { + val resourceUri: String = ... + + val body: String = webClient + .get() + .uri(resourceUri) + .attributes(clientRegistrationId("okta")) <1> + .retrieve() + .bodyToMono() + .block() + + ... + + return "index" +} +---- +==== +<1> `clientRegistrationId()` is a `static` method in `ServletOAuth2AuthorizedClientExchangeFilterFunction`. + + +=== Defaulting the Authorized Client + +If neither `OAuth2AuthorizedClient` or `ClientRegistration.getRegistrationId()` is provided as a request attribute, the `ServletOAuth2AuthorizedClientExchangeFilterFunction` can determine the _default_ client to use depending on it's configuration. + +If `setDefaultOAuth2AuthorizedClient(true)` is configured and the user has authenticated using `HttpSecurity.oauth2Login()`, the `OAuth2AccessToken` associated with the current `OAuth2AuthenticationToken` is used. + +The following code shows the specific configuration: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultOAuth2AuthorizedClient(true); + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { + val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultOAuth2AuthorizedClient(true) + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build() +} +---- +==== + +[WARNING] +It is recommended to be cautious with this feature since all HTTP requests will receive the access token. + +Alternatively, if `setDefaultClientRegistrationId("okta")` is configured with a valid `ClientRegistration`, the `OAuth2AccessToken` associated with the `OAuth2AuthorizedClient` is used. + +The following code shows the specific configuration: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = + new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth2Client.setDefaultClientRegistrationId("okta"); + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun webClient(authorizedClientManager: OAuth2AuthorizedClientManager?): WebClient { + val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) + oauth2Client.setDefaultClientRegistrationId("okta") + return WebClient.builder() + .apply(oauth2Client.oauth2Configuration()) + .build() +} +---- +==== + +[WARNING] +It is recommended to be cautious with this feature since all HTTP requests will receive the access token. diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/client-authentication.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/client-authentication.adoc new file mode 100644 index 0000000000..630c72b18c --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/client-authentication.adoc @@ -0,0 +1,165 @@ +[[oauth2Client-client-auth-support]] += Client Authentication Support + + +[[oauth2Client-jwt-bearer-auth]] +== JWT Bearer + +[NOTE] +Please refer to JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants for further details on https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] Client Authentication. + +The default implementation for JWT Bearer Client Authentication is `NimbusJwtClientAuthenticationParametersConverter`, +which is a `Converter` that customizes the Token Request parameters by adding +a signed JSON Web Token (JWS) in the `client_assertion` parameter. + +The `java.security.PrivateKey` or `javax.crypto.SecretKey` used for signing the JWS +is supplied by the `com.nimbusds.jose.jwk.JWK` resolver associated with `NimbusJwtClientAuthenticationParametersConverter`. + + +=== Authenticate using `private_key_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-authentication-method: private_key_jwt + authorization-grant-type: authorization_code + ... +---- + +The following example shows how to configure `DefaultAuthorizationCodeTokenResponseClient`: + +==== +.Java +[source,java,role="primary"] +---- +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + RSAPublicKey publicKey = ... + RSAPrivateKey privateKey = ... + return new RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +OAuth2AuthorizationCodeGrantRequestEntityConverter requestEntityConverter = + new OAuth2AuthorizationCodeGrantRequestEntityConverter(); +requestEntityConverter.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); + +DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = + new DefaultAuthorizationCodeTokenResponseClient(); +tokenResponseClient.setRequestEntityConverter(requestEntityConverter); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val jwkResolver: Function = + Function { clientRegistration -> + if (clientRegistration.clientAuthenticationMethod.equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) { + // Assuming RSA key type + var publicKey: RSAPublicKey + var privateKey: RSAPrivateKey + RSAKey.Builder(publicKey) = //... + .privateKey(privateKey) = //... + .keyID(UUID.randomUUID().toString()) + .build() + } + null + } + +val requestEntityConverter = OAuth2AuthorizationCodeGrantRequestEntityConverter() +requestEntityConverter.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) + +val tokenResponseClient = DefaultAuthorizationCodeTokenResponseClient() +tokenResponseClient.setRequestEntityConverter(requestEntityConverter) +---- +==== + + +=== Authenticate using `client_secret_jwt` + +Given the following Spring Boot 2.x properties for an OAuth 2.0 Client registration: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + client-authentication-method: client_secret_jwt + authorization-grant-type: client_credentials + ... +---- + +The following example shows how to configure `DefaultClientCredentialsTokenResponseClient`: + +==== +.Java +[source,java,role="primary"] +---- +Function jwkResolver = (clientRegistration) -> { + if (clientRegistration.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) { + SecretKeySpec secretKey = new SecretKeySpec( + clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), + "HmacSHA256"); + return new OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build(); + } + return null; +}; + +OAuth2ClientCredentialsGrantRequestEntityConverter requestEntityConverter = + new OAuth2ClientCredentialsGrantRequestEntityConverter(); +requestEntityConverter.addParametersConverter( + new NimbusJwtClientAuthenticationParametersConverter<>(jwkResolver)); + +DefaultClientCredentialsTokenResponseClient tokenResponseClient = + new DefaultClientCredentialsTokenResponseClient(); +tokenResponseClient.setRequestEntityConverter(requestEntityConverter); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val jwkResolver = Function { clientRegistration: ClientRegistration -> + if (clientRegistration.clientAuthenticationMethod == ClientAuthenticationMethod.CLIENT_SECRET_JWT) { + val secretKey = SecretKeySpec( + clientRegistration.clientSecret.toByteArray(StandardCharsets.UTF_8), + "HmacSHA256" + ) + OctetSequenceKey.Builder(secretKey) + .keyID(UUID.randomUUID().toString()) + .build() + } + null +} + +val requestEntityConverter = OAuth2ClientCredentialsGrantRequestEntityConverter() +requestEntityConverter.addParametersConverter( + NimbusJwtClientAuthenticationParametersConverter(jwkResolver) +) + +val tokenResponseClient = DefaultClientCredentialsTokenResponseClient() +tokenResponseClient.setRequestEntityConverter(requestEntityConverter) +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc new file mode 100644 index 0000000000..e02d387d1f --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc @@ -0,0 +1,440 @@ +[[oauth2Client-core-interface-class]] += Core Interfaces / Classes + + +[[oauth2Client-client-registration]] +== ClientRegistration + +`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider. + +A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details. + +`ClientRegistration` and its properties are defined as follows: + +[source,java] +---- +public final class ClientRegistration { + private String registrationId; <1> + private String clientId; <2> + private String clientSecret; <3> + private ClientAuthenticationMethod clientAuthenticationMethod; <4> + private AuthorizationGrantType authorizationGrantType; <5> + private String redirectUri; <6> + private Set scopes; <7> + private ProviderDetails providerDetails; + private String clientName; <8> + + public class ProviderDetails { + private String authorizationUri; <9> + private String tokenUri; <10> + private UserInfoEndpoint userInfoEndpoint; + private String jwkSetUri; <11> + private String issuerUri; <12> + private Map configurationMetadata; <13> + + public class UserInfoEndpoint { + private String uri; <14> + private AuthenticationMethod authenticationMethod; <15> + private String userNameAttributeName; <16> + + } + } +} +---- +<1> `registrationId`: The ID that uniquely identifies the `ClientRegistration`. +<2> `clientId`: The client identifier. +<3> `clientSecret`: The client secret. +<4> `clientAuthenticationMethod`: The method used to authenticate the Client with the Provider. +The supported values are *client_secret_basic*, *client_secret_post*, *private_key_jwt*, *client_secret_jwt* and *none* https://tools.ietf.org/html/rfc6749#section-2.1[(public clients)]. +<5> `authorizationGrantType`: The OAuth 2.0 Authorization Framework defines four https://tools.ietf.org/html/rfc6749#section-1.3[Authorization Grant] types. + The supported values are `authorization_code`, `client_credentials`, `password`, as well as, extension grant type `urn:ietf:params:oauth:grant-type:jwt-bearer`. +<6> `redirectUri`: The client's registered redirect URI that the _Authorization Server_ redirects the end-user's user-agent + to after the end-user has authenticated and authorized access to the client. +<7> `scopes`: The scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile. +<8> `clientName`: A descriptive name used for the client. +The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page. +<9> `authorizationUri`: The Authorization Endpoint URI for the Authorization Server. +<10> `tokenUri`: The Token Endpoint URI for the Authorization Server. +<11> `jwkSetUri`: The URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] Set from the Authorization Server, + which contains the cryptographic key(s) used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the ID Token and optionally the UserInfo Response. +<12> `issuerUri`: Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth 2.0 Authorization Server. +<13> `configurationMetadata`: The https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration Information]. + This information will only be available if the Spring Boot 2.x property `spring.security.oauth2.client.provider.[providerId].issuerUri` is configured. +<14> `(userInfoEndpoint)uri`: The UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user. +<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint. +The supported values are *header*, *form* and *query*. +<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user. + +A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint]. + +`ClientRegistrations` provides convenience methods for configuring a `ClientRegistration` in this way, as can be seen in the following example: + +==== +.Java +[source,java,role="primary"] +---- +ClientRegistration clientRegistration = + ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build() +---- +==== + +The above code will query in series `https://idp.example.com/issuer/.well-known/openid-configuration`, and then `https://idp.example.com/.well-known/openid-configuration/issuer`, and finally `https://idp.example.com/.well-known/oauth-authorization-server/issuer`, stopping at the first to return a 200 response. + +As an alternative, you can use `ClientRegistrations.fromOidcIssuerLocation()` to only query the OpenID Connect Provider's Configuration endpoint. + +[[oauth2Client-client-registration-repo]] +== ClientRegistrationRepository + +The `ClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s). + +[NOTE] +Client registration information is ultimately stored and owned by the associated Authorization Server. +This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server. + +Spring Boot 2.x auto-configuration binds each of the properties under `spring.security.oauth2.client.registration._[registrationId]_` to an instance of `ClientRegistration` and then composes each of the `ClientRegistration` instance(s) within a `ClientRegistrationRepository`. + +[NOTE] +The default implementation of `ClientRegistrationRepository` is `InMemoryClientRegistrationRepository`. + +The auto-configuration also registers the `ClientRegistrationRepository` as a `@Bean` in the `ApplicationContext` so that it is available for dependency-injection, if needed by the application. + +The following listing shows an example: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private ClientRegistrationRepository clientRegistrationRepository; + + @GetMapping("/") + public String index() { + ClientRegistration oktaRegistration = + this.clientRegistrationRepository.findByRegistrationId("okta"); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var clientRegistrationRepository: ClientRegistrationRepository + + @GetMapping("/") + fun index(): String { + val oktaRegistration = + this.clientRegistrationRepository.findByRegistrationId("okta") + + //... + + return "index"; + } +} +---- +==== + +[[oauth2Client-authorized-client]] +== OAuth2AuthorizedClient + +`OAuth2AuthorizedClient` is a representation of an Authorized Client. +A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources. + +`OAuth2AuthorizedClient` serves the purpose of associating an `OAuth2AccessToken` (and optional `OAuth2RefreshToken`) to a `ClientRegistration` (client) and resource owner, who is the `Principal` end-user that granted the authorization. + + +[[oauth2Client-authorized-repo-service]] +== OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService + +`OAuth2AuthorizedClientRepository` is responsible for persisting `OAuth2AuthorizedClient`(s) between web requests. +Whereas, the primary role of `OAuth2AuthorizedClientService` is to manage `OAuth2AuthorizedClient`(s) at the application-level. + +From a developer perspective, the `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` provides the capability to lookup an `OAuth2AccessToken` associated with a client so that it may be used to initiate a protected resource request. + +The following listing shows an example: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class OAuth2ClientController { + + @Autowired + private OAuth2AuthorizedClientService authorizedClientService; + + @GetMapping("/") + public String index(Authentication authentication) { + OAuth2AuthorizedClient authorizedClient = + this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); + + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + + ... + + return "index"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class OAuth2ClientController { + + @Autowired + private lateinit var authorizedClientService: OAuth2AuthorizedClientService + + @GetMapping("/") + fun index(authentication: Authentication): String { + val authorizedClient: OAuth2AuthorizedClient = + this.authorizedClientService.loadAuthorizedClient("okta", authentication.getName()); + val accessToken = authorizedClient.accessToken + + ... + + return "index"; + } +} +---- +==== + +[NOTE] +Spring Boot 2.x auto-configuration registers an `OAuth2AuthorizedClientRepository` and/or `OAuth2AuthorizedClientService` `@Bean` in the `ApplicationContext`. +However, the application may choose to override and register a custom `OAuth2AuthorizedClientRepository` or `OAuth2AuthorizedClientService` `@Bean`. + +The default implementation of `OAuth2AuthorizedClientService` is `InMemoryOAuth2AuthorizedClientService`, which stores `OAuth2AuthorizedClient`(s) in-memory. + +Alternatively, the JDBC implementation `JdbcOAuth2AuthorizedClientService` may be configured for persisting `OAuth2AuthorizedClient`(s) in a database. + +[NOTE] +`JdbcOAuth2AuthorizedClientService` depends on the table definition described in xref:servlet/appendix/database-schema.adoc#dbschema-oauth2-client[ OAuth 2.0 Client Schema]. + + +[[oauth2Client-authorized-manager-provider]] +== OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider + +The `OAuth2AuthorizedClientManager` is responsible for the overall management of `OAuth2AuthorizedClient`(s). + +The primary responsibilities include: + +* Authorizing (or re-authorizing) an OAuth 2.0 Client, using an `OAuth2AuthorizedClientProvider`. +* Delegating the persistence of an `OAuth2AuthorizedClient`, typically using an `OAuth2AuthorizedClientService` or `OAuth2AuthorizedClientRepository`. +* Delegating to an `OAuth2AuthorizationSuccessHandler` when an OAuth 2.0 Client has been successfully authorized (or re-authorized). +* Delegating to an `OAuth2AuthorizationFailureHandler` when an OAuth 2.0 Client fails to authorize (or re-authorize). + +An `OAuth2AuthorizedClientProvider` implements a strategy for authorizing (or re-authorizing) an OAuth 2.0 Client. +Implementations will typically implement an authorization grant type, eg. `authorization_code`, `client_credentials`, etc. + +The default implementation of `OAuth2AuthorizedClientManager` is `DefaultOAuth2AuthorizedClientManager`, which is associated with an `OAuth2AuthorizedClientProvider` that may support multiple authorization grant types using a delegation-based composite. +The `OAuth2AuthorizedClientProviderBuilder` may be used to configure and build the delegation-based composite. + +The following code shows an example of how to configure and build an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== + +When an authorization attempt succeeds, the `DefaultOAuth2AuthorizedClientManager` will delegate to the `OAuth2AuthorizationSuccessHandler`, which (by default) will save the `OAuth2AuthorizedClient` via the `OAuth2AuthorizedClientRepository`. +In the case of a re-authorization failure, eg. a refresh token is no longer valid, the previously saved `OAuth2AuthorizedClient` will be removed from the `OAuth2AuthorizedClientRepository` via the `RemoveAuthorizedClientOAuth2AuthorizationFailureHandler`. +The default behaviour may be customized via `setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)` and `setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)`. + +The `DefaultOAuth2AuthorizedClientManager` is also associated with a `contextAttributesMapper` of type `Function>`, which is responsible for mapping attribute(s) from the `OAuth2AuthorizeRequest` to a `Map` of attributes to be associated to the `OAuth2AuthorizationContext`. +This can be useful when you need to supply an `OAuth2AuthorizedClientProvider` with required (supported) attribute(s), eg. the `PasswordOAuth2AuthorizedClientProvider` requires the resource owner's `username` and `password` to be available in `OAuth2AuthorizationContext.getAttributes()`. + +The following code shows an example of the `contextAttributesMapper`: + +==== +.Java +[source,java,role="primary"] +---- +@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> contextAttributesMapper() { + return authorizeRequest -> { + Map 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; + }; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@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> { + return Function { authorizeRequest -> + var contextAttributes: MutableMap = mutableMapOf() + val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name) + val username: String = servletRequest.getParameter(OAuth2ParameterNames.USERNAME) + val password: String = 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 + } +} +---- +==== + +The `DefaultOAuth2AuthorizedClientManager` is designed to be used *_within_* the context of a `HttpServletRequest`. +When operating *_outside_* of a `HttpServletRequest` context, use `AuthorizedClientServiceOAuth2AuthorizedClientManager` instead. + +A _service application_ is a common use case for when to use an `AuthorizedClientServiceOAuth2AuthorizedClientManager`. +Service applications often run in the background, without any user interaction, and typically run under a system-level account instead of a user account. +An OAuth 2.0 Client configured with the `client_credentials` grant type can be considered a type of service application. + +The following code shows an example of how to configure an `AuthorizedClientServiceOAuth2AuthorizedClientManager` that provides support for the `client_credentials` grant type: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientService authorizedClientService) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = + new AuthorizedClientServiceOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientService: OAuth2AuthorizedClientService): OAuth2AuthorizedClientManager { + val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build() + val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/client/index.adoc b/docs/modules/ROOT/pages/servlet/oauth2/client/index.adoc new file mode 100644 index 0000000000..7ed080bab3 --- /dev/null +++ b/docs/modules/ROOT/pages/servlet/oauth2/client/index.adoc @@ -0,0 +1,146 @@ +[[oauth2client]] += OAuth 2.0 Client +:page-section-summary-toc: 1 + +The OAuth 2.0 Client features provide support for the Client role as defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework]. + +At a high-level, the core features available are: + +.Authorization Grant support +* https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] +* https://tools.ietf.org/html/rfc6749#section-6[Refresh Token] +* https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] +* https://tools.ietf.org/html/rfc6749#section-1.3.3[Resource Owner Password Credentials] +* https://datatracker.ietf.org/doc/html/rfc7523#section-2.1[JWT Bearer] + +.Client Authentication support +* https://datatracker.ietf.org/doc/html/rfc7523#section-2.2[JWT Bearer] + +.HTTP Client support +* xref:servlet/oauth2/client/authorized-clients.adoc#oauth2Client-webclient-servlet[`WebClient` integration for Servlet Environments] (for requesting protected resources) + +The `HttpSecurity.oauth2Client()` DSL provides a number of configuration options for customizing the core components used by OAuth 2.0 Client. +In addition, `HttpSecurity.oauth2Client().authorizationCodeGrant()` enables the customization of the Authorization Code grant. + +The following code shows the complete configuration options provided by the `HttpSecurity.oauth2Client()` DSL: + +.OAuth2 Client Configuration Options +==== +.Java +[source,java,role="primary"] +---- +@EnableWebSecurity +public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .oauth2Client(oauth2 -> oauth2 + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizedClientService(this.authorizedClientService()) + .authorizationCodeGrant(codeGrant -> codeGrant + .authorizationRequestRepository(this.authorizationRequestRepository()) + .authorizationRequestResolver(this.authorizationRequestResolver()) + .accessTokenResponseClient(this.accessTokenResponseClient()) + ) + ); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebSecurity +class OAuth2ClientSecurityConfig : WebSecurityConfigurerAdapter() { + + override fun configure(http: HttpSecurity) { + http { + oauth2Client { + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizedClientService = authorizedClientService() + authorizationCodeGrant { + authorizationRequestRepository = authorizationRequestRepository() + authorizationRequestResolver = authorizationRequestResolver() + accessTokenResponseClient = accessTokenResponseClient() + } + } + } + } +} +---- +==== + +In addition to the `HttpSecurity.oauth2Client()` DSL, XML configuration is also supported. + +The following code shows the complete configuration options available in the xref:servlet/appendix/namespace/http.adoc#nsa-oauth2-client[ security namespace]: + +.OAuth2 Client XML Configuration Options +==== +[source,xml] +---- + + + + + +---- +==== + +The `OAuth2AuthorizedClientManager` is responsible for managing the authorization (or re-authorization) of an OAuth 2.0 Client, in collaboration with one or more `OAuth2AuthorizedClientProvider`(s). + +The following code shows an example of how to register an `OAuth2AuthorizedClientManager` `@Bean` and associate it with an `OAuth2AuthorizedClientProvider` composite that provides support for the `authorization_code`, `refresh_token`, `client_credentials` and `password` authorization grant types: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +public OAuth2AuthorizedClientManager authorizedClientManager( + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AuthorizedClientRepository authorizedClientRepository) { + + OAuth2AuthorizedClientProvider authorizedClientProvider = + OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build(); + + DefaultOAuth2AuthorizedClientManager authorizedClientManager = + new DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + return authorizedClientManager; +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +fun authorizedClientManager( + clientRegistrationRepository: ClientRegistrationRepository, + authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager { + val authorizedClientProvider: OAuth2AuthorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .authorizationCode() + .refreshToken() + .clientCredentials() + .password() + .build() + val authorizedClientManager = DefaultOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientRepository) + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) + return authorizedClientManager +} +---- +==== diff --git a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc b/docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc index e30a4e407b..c80b82b743 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/oauth2-login.adoc @@ -40,10 +40,10 @@ The redirect URI is the path in the application that the end-user's user-agent i In the "Set a redirect URI" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. TIP: The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. -The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration]. +The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[ClientRegistration]. IMPORTANT: If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. -Also, see the supported xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. +Also, see the supported xref:servlet/oauth2/client/authorization-grants.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. [[oauth2login-sample-application-config]] @@ -69,7 +69,7 @@ spring: .OAuth Client properties ==== <1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. -<2> Following the base property prefix is the ID for the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration], such as google. +<2> Following the base property prefix is the ID for the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[ClientRegistration], such as google. ==== . Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. @@ -93,7 +93,7 @@ At this point, the OAuth Client retrieves your email address and basic profile i [[oauth2login-boot-property-mappings]] == Spring Boot 2.x Property Mappings -The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:servlet/oauth2/oauth2-client.adoc#oauth2Client-client-registration[ClientRegistration] properties. +The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[ClientRegistration] properties. |=== |Spring Boot 2.x |ClientRegistration diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc index 9c35a4b87d..a9a1877aff 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/bearer-tokens.adoc @@ -241,7 +241,7 @@ fun rest(): RestTemplate { [NOTE] Unlike the {security-api-url}org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.html[OAuth 2.0 Authorized Client Manager], this filter interceptor makes no attempt to renew the token, should it be expired. -To obtain this level of support, please create an interceptor using the xref:servlet/oauth2/oauth2-client.adoc#oauth2client[OAuth 2.0 Authorized Client Manager]. +To obtain this level of support, please create an interceptor using the xref:servlet/oauth2/client/index.adoc#oauth2client[OAuth 2.0 Authorized Client Manager]. [[oauth2resourceserver-bearertoken-failure]] == Bearer Token Failure