1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549 |
- [[oauth2-client-authorization-grants]]
- = [[oauth2Client-auth-grant-support]]Authorization Grant Support
- :spring-security-reference-base-url: https://docs.spring.io/spring-security/reference
- This section describes Spring Security's support for authorization grants.
- [[oauth2-client-authorization-code]]
- == [[oauth2Client-auth-code-grant]]Authorization Code
- [NOTE]
- ====
- See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant.
- ====
- [[oauth2-client-authorization-code-authorization]]
- === Obtaining Authorization
- [NOTE]
- ====
- See the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant.
- ====
- [[oauth2-client-authorization-code-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.
- The primary role of the `OAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request.
- The default implementation `DefaultOAuth2AuthorizationRequestResolver` matches on the (default) path `+/oauth2/authorization/{registrationId}+`, extracting the `registrationId`, and using it to build the `OAuth2AuthorizationRequest` for the associated `ClientRegistration`.
- Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
- [source,yaml,attrs="-attributes"]
- ----
- spring:
- security:
- oauth2:
- client:
- registration:
- okta:
- client-id: okta-client-id
- client-secret: okta-client-secret
- authorization-grant-type: authorization_code
- redirect-uri: "{baseUrl}/authorized/okta"
- scope: read, write
- provider:
- okta:
- authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize
- token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
- ----
- Given the preceding properties, a request with the base path `/oauth2/authorization/okta` initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter` and ultimately starts the Authorization Code grant flow.
- [NOTE]
- ====
- The `AuthorizationCodeOAuth2AuthorizedClientProvider` is an implementation of `OAuth2AuthorizedClientProvider` for the Authorization Code grant,
- which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter`.
- ====
- If the OAuth 2.0 Client is a https://tools.ietf.org/html/rfc6749#section-2.1[Public Client], configure the OAuth 2.0 Client registration as follows:
- [source,yaml,attrs="-attributes"]
- ----
- spring:
- security:
- oauth2:
- client:
- registration:
- okta:
- client-id: okta-client-id
- client-authentication-method: none
- authorization-grant-type: authorization_code
- redirect-uri: "{baseUrl}/authorized/okta"
- # ...
- ----
- Public Clients are supported by using https://tools.ietf.org/html/rfc7636[Proof Key for Code Exchange] (PKCE).
- If the client is running in an untrusted environment (such as a native application or web browser-based application) and is therefore incapable of maintaining the confidentiality of its credentials, PKCE is automatically used when the following conditions are true:
- . `client-secret` is omitted (or empty) and
- . `client-authentication-method` is set to `none` (`ClientAuthenticationMethod.NONE`)
- or
- . When `ClientRegistration.clientSettings.requireProofKey` is `true` (in this case `ClientRegistration.authorizationGrantType` must be `authorization_code`)
- [TIP]
- ====
- If the OAuth 2.0 Provider supports PKCE for https://tools.ietf.org/html/rfc6749#section-2.1[Confidential Clients], you may (optionally) configure it using `DefaultOAuth2AuthorizationRequestResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce())`.
- ====
- [[oauth2-client-authorization-code-redirect-uri]]
- [[oauth2Client-auth-code-redirect-uri]]The `DefaultOAuth2AuthorizationRequestResolver` also supports `URI` template variables for the `redirect-uri` by using `UriComponentsBuilder`.
- The following configuration uses all the supported `URI` template variables:
- [source,yaml,attrs="-attributes"]
- ----
- spring:
- security:
- oauth2:
- client:
- registration:
- okta:
- # ...
- redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
- # ...
- ----
- [NOTE]
- ====
- `+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+`
- ====
- 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].
- Doing so ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`.
- [[oauth2-client-authorization-code-authorization-request-resolver]]
- === 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.
- For example, OpenID Connect defines additional OAuth 2.0 request parameters for the https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest[Authorization Code Flow] extending from the standard parameters defined in the https://tools.ietf.org/html/rfc6749#section-4.1.1[OAuth 2.0 Authorization Framework].
- One of those extended parameters is the `prompt` parameter.
- [NOTE]
- ====
- The `prompt` parameter is optional. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for re-authentication and consent. The defined values are: `none`, `login`, `consent`, and `select_account`.
- ====
- The following example shows how to configure the `DefaultOAuth2AuthorizationRequestResolver` with a `Consumer<OAuth2AuthorizationRequest.Builder>` that customizes the Authorization Request for `oauth2Login()`, by including the request parameter `prompt=consent`.
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Configuration
- @EnableWebSecurity
- public class OAuth2LoginSecurityConfig {
- @Autowired
- private ClientRegistrationRepository clientRegistrationRepository;
- @Bean
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http
- .authorizeHttpRequests((authorize) -> authorize
- .anyRequest().authenticated()
- )
- .oauth2Login((oauth2) -> oauth2
- .authorizationEndpoint((authorization) -> authorization
- .authorizationRequestResolver(
- authorizationRequestResolver(this.clientRegistrationRepository)
- )
- )
- );
- return http.build();
- }
- private OAuth2AuthorizationRequestResolver authorizationRequestResolver(
- ClientRegistrationRepository clientRegistrationRepository) {
- DefaultOAuth2AuthorizationRequestResolver authorizationRequestResolver =
- new DefaultOAuth2AuthorizationRequestResolver(
- clientRegistrationRepository, "/oauth2/authorization");
- authorizationRequestResolver.setAuthorizationRequestCustomizer(
- authorizationRequestCustomizer());
- return authorizationRequestResolver;
- }
- private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
- return customizer -> customizer
- .additionalParameters((params) -> params.put("prompt", "consent"));
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Configuration
- @EnableWebSecurity
- class SecurityConfig {
- @Autowired
- private lateinit var customClientRegistrationRepository: ClientRegistrationRepository
- @Bean
- open fun filterChain(http: HttpSecurity): SecurityFilterChain {
- http {
- authorizeRequests {
- authorize(anyRequest, authenticated)
- }
- oauth2Login {
- authorizationEndpoint {
- authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
- }
- }
- }
- return http.build()
- }
- private fun authorizationRequestResolver(
- clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver {
- val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver(
- clientRegistrationRepository, "/oauth2/authorization")
- authorizationRequestResolver.setAuthorizationRequestCustomizer(
- authorizationRequestCustomizer())
- return authorizationRequestResolver
- }
- private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
- return Consumer { customizer ->
- customizer
- .additionalParameters { params -> params["prompt"] = "consent" }
- }
- }
- }
- ----
- ======
- For the simple use case where the additional request parameter is always the same for a specific provider, you can add it directly in the `authorization-uri` property.
- For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, you can configure it as follows:
- [source,yaml]
- ----
- spring:
- security:
- oauth2:
- client:
- provider:
- okta:
- authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
- ----
- The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
- Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
- [TIP]
- ====
- `OAuth2AuthorizationRequest.Builder.build()` constructs the `OAuth2AuthorizationRequest.authorizationRequestUri`, which represents the Authorization Request URI including all query parameters using the `application/x-www-form-urlencoded` format.
- ====
- The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
- return customizer -> customizer
- .authorizationRequestUri((uriBuilder) -> uriBuilder
- .queryParam("prompt", "consent").build());
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
- return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
- customizer
- .authorizationRequestUri { uriBuilder: UriBuilder ->
- uriBuilder
- .queryParam("prompt", "consent").build()
- }
- }
- }
- ----
- ======
- [[oauth2-client-authorization-code-authorization-request-repository]]
- === Storing the Authorization Request
- The `AuthorizationRequestRepository` is responsible for the persistence of the `OAuth2AuthorizationRequest` from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback).
- [TIP]
- ====
- The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.
- ====
- The default implementation of `AuthorizationRequestRepository` is `HttpSessionOAuth2AuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `HttpSession`.
- If you have a custom implementation of `AuthorizationRequestRepository`, you can configure it as follows:
- .AuthorizationRequestRepository Configuration
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Configuration
- @EnableWebSecurity
- public class OAuth2ClientSecurityConfig {
- @Bean
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http
- .oauth2Client((oauth2) -> oauth2
- .authorizationCodeGrant((codeGrant) -> codeGrant
- .authorizationRequestRepository(this.authorizationRequestRepository())
- // ...
- )
- )
- .oauth2Login((oauth2) -> oauth2
- .authorizationEndpoint((endpoint) -> endpoint
- .authorizationRequestRepository(this.authorizationRequestRepository())
- // ...
- )
- );
- return http.build();
- }
- @Bean
- public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
- return new CustomOAuth2AuthorizationRequestRepository();
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Configuration
- @EnableWebSecurity
- class OAuth2ClientSecurityConfig {
- @Bean
- open fun filterChain(http: HttpSecurity): SecurityFilterChain {
- http {
- oauth2Client {
- authorizationCodeGrant {
- authorizationRequestRepository = authorizationRequestRepository()
- }
- }
- }
- return http.build()
- }
- }
- ----
- Xml::
- +
- [source,xml,role="secondary"]
- ----
- <http>
- <oauth2-client>
- <authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
- </oauth2-client>
- </http>
- ----
- ======
- [[oauth2-client-authorization-code-access-token]]
- === Requesting an Access Token
- [NOTE]
- ====
- See the https://tools.ietf.org/html/rfc6749#section-4.1.3[Access Token Request/Response] protocol flow for the Authorization Code grant.
- ====
- There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Authorization Code grant:
- * `DefaultAuthorizationCodeTokenResponseClient` (_default_)
- * `RestClientAuthorizationCodeTokenResponseClient`
- The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
- Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
- [NOTE]
- ====
- This section focuses on `RestClientAuthorizationCodeTokenResponseClient`.
- You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token[`DefaultAuthorizationCodeTokenResponseClient`] in the Spring Security 6.3 documentation.
- ====
- :section-id: authorization-code
- :grant-type: Authorization Code
- :class-name: RestClientAuthorizationCodeTokenResponseClient
- :grant-request: OAuth2AuthorizationCodeGrantRequest
- :leveloffset: +1
- include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
- :leveloffset: -1
- [[oauth2-client-authorization-code-access-token-response-client-dsl]]
- === Customize using the DSL
- Whether you customize `{class-name}` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the DSL (as an alternative to <<oauth2-client-authorization-code-access-token-response-client-bean,publishing a bean>>) as follows:
- .Access Token Response Configuration via DSL
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Configuration
- @EnableWebSecurity
- public class OAuth2ClientSecurityConfig {
- @Bean
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http
- .oauth2Client((oauth2) -> oauth2
- .authorizationCodeGrant((codeGrant) -> codeGrant
- .accessTokenResponseClient(this.accessTokenResponseClient())
- // ...
- )
- );
- return http.build();
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Configuration
- @EnableWebSecurity
- class OAuth2ClientSecurityConfig {
- @Bean
- open fun filterChain(http: HttpSecurity): SecurityFilterChain {
- http {
- oauth2Client {
- authorizationCodeGrant {
- accessTokenResponseClient = accessTokenResponseClient()
- }
- }
- }
- return http.build()
- }
- }
- ----
- Xml::
- +
- [source,xml,role="secondary"]
- ----
- <http>
- <oauth2-client>
- <authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
- </oauth2-client>
- </http>
- ----
- ======
- [[oauth2-client-refresh-token]]
- == [[oauth2Client-refresh-token-grant]]Refresh Token
- [NOTE]
- ====
- See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token].
- ====
- [[oauth2-client-refresh-token-access-token]]
- === Refreshing an Access Token
- [NOTE]
- ====
- See the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant.
- ====
- There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Refresh Token grant:
- * `DefaultRefreshTokenTokenResponseClient` (_default_)
- * `RestClientRefreshTokenTokenResponseClient`
- The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
- Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
- [NOTE]
- ====
- This section focuses on `RestClientRefreshTokenTokenResponseClient`.
- You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_refreshing_an_access_token[`DefaultRefreshTokenTokenResponseClient`] in the Spring Security 6.3 documentation.
- ====
- :section-id: refresh-token
- :grant-type: Refresh Token
- :class-name: RestClientRefreshTokenTokenResponseClient
- :grant-request: OAuth2RefreshTokenGrantRequest
- :leveloffset: +1
- include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
- :leveloffset: -1
- [[oauth2-client-refresh-token-authorized-client-provider-builder]]
- === Customize using the Builder
- Whether you customize `RestClientRefreshTokenTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-refresh-token-access-token-response-client-bean,publishing a bean>>) as follows:
- .Access Token Response Configuration via Builder
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- // Customize
- OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .authorizationCode()
- .refreshToken((configurer) -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
- .build();
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- // Customize
- val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .authorizationCode()
- .refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
- .build()
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- ----
- ======
- [NOTE]
- ====
- `OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenOAuth2AuthorizedClientProvider`,
- which is an implementation of an `OAuth2AuthorizedClientProvider` for the Refresh Token grant.
- ====
- The `OAuth2RefreshToken` can optionally be returned in the Access Token Response for the `authorization_code` and `password` grant types.
- If the `OAuth2AuthorizedClient.getRefreshToken()` is available and the `OAuth2AuthorizedClient.getAccessToken()` is expired, it is automatically refreshed by the `RefreshTokenOAuth2AuthorizedClientProvider`.
- [[oauth2-client-client-credentials]]
- == [[oauth2Client-client-creds-grant]]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.
- ====
- [[oauth2-client-client-credentials-access-token]]
- === Requesting an Access Token
- [NOTE]
- ====
- See the https://tools.ietf.org/html/rfc6749#section-4.4.2[Access Token Request/Response] protocol flow for the Client Credentials grant.
- ====
- There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Client Credentials grant:
- * `DefaultClientCredentialsTokenResponseClient` (_default_)
- * `RestClientClientCredentialsTokenResponseClient`
- The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
- Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
- [NOTE]
- ====
- This section focuses on `RestClientClientCredentialsTokenResponseClient`.
- You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token_2[`DefaultClientCredentialsTokenResponseClient`] in the Spring Security 6.3 documentation.
- ====
- :section-id: client-credentials
- :grant-type: Client Credentials
- :class-name: RestClientClientCredentialsTokenResponseClient
- :grant-request: OAuth2ClientCredentialsGrantRequest
- :leveloffset: +1
- include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
- :leveloffset: -1
- [[oauth2-client-client-credentials-authorized-client-provider-builder]]
- === Customize using the Builder
- Whether you customize `RestClientClientCredentialsTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-client-credentials-access-token-response-client-bean,publishing a bean>>) as follows:
- .Access Token Response Configuration via Builder
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- // Customize
- OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .clientCredentials((configurer) -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
- .build();
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- // Customize
- val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
- .build()
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- ----
- ======
- [NOTE]
- ====
- `OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsOAuth2AuthorizedClientProvider`,
- which is an implementation of an `OAuth2AuthorizedClientProvider` for the Client Credentials grant.
- ====
- [[oauth2-client-client-credentials-authorized-client-manager]]
- === Using the Access Token
- Consider the following Spring Boot 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
- authorization-grant-type: client_credentials
- scope: read, write
- provider:
- okta:
- token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
- ----
- Further consider the following `OAuth2AuthorizedClientManager` `@Bean`:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Bean
- public OAuth2AuthorizedClientManager authorizedClientManager(
- ClientRegistrationRepository clientRegistrationRepository,
- OAuth2AuthorizedClientRepository authorizedClientRepository) {
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .clientCredentials()
- .build();
- DefaultOAuth2AuthorizedClientManager authorizedClientManager =
- new DefaultOAuth2AuthorizedClientManager(
- clientRegistrationRepository, authorizedClientRepository);
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- return authorizedClientManager;
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun authorizedClientManager(
- clientRegistrationRepository: ClientRegistrationRepository,
- authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .clientCredentials()
- .build()
- val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
- clientRegistrationRepository, authorizedClientRepository)
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- return authorizedClientManager
- }
- ----
- ======
- Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Controller
- public class OAuth2ClientController {
- @Autowired
- private OAuth2AuthorizedClientManager authorizedClientManager;
- @GetMapping("/")
- public String index(Authentication authentication,
- HttpServletRequest servletRequest,
- HttpServletResponse servletResponse) {
- OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(authentication)
- .attributes(attrs -> {
- attrs.put(HttpServletRequest.class.getName(), servletRequest);
- attrs.put(HttpServletResponse.class.getName(), servletResponse);
- })
- .build();
- OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
- OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
- // ...
- return "index";
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- class OAuth2ClientController {
- @Autowired
- private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
- @GetMapping("/")
- fun index(authentication: Authentication?,
- servletRequest: HttpServletRequest,
- servletResponse: HttpServletResponse): String {
- val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(authentication)
- .attributes(Consumer { attrs: MutableMap<String, Any> ->
- attrs[HttpServletRequest::class.java.name] = servletRequest
- attrs[HttpServletResponse::class.java.name] = servletResponse
- })
- .build()
- val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
- val accessToken: OAuth2AccessToken = authorizedClient.accessToken
- // ...
- return "index"
- }
- }
- ----
- ======
- [NOTE]
- ====
- `HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes.
- If not provided, they default to `ServletRequestAttributes` by using `RequestContextHolder.getRequestAttributes()`.
- ====
- [[oauth2-client-password]]
- == [[oauth2Client-password-grant]]Resource Owner Password Credentials
- [NOTE]
- ====
- See 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.
- ====
- [[oauth2-client-password-access-token]]
- === Requesting an Access Token
- [NOTE]
- ====
- See the https://tools.ietf.org/html/rfc6749#section-4.3.2[Access Token Request/Response] protocol flow for the Resource Owner Password Credentials grant.
- ====
- The default implementation of `OAuth2AccessTokenResponseClient` for the Resource Owner Password Credentials grant is `DefaultPasswordTokenResponseClient`, which uses a `RestOperations` when requesting an access token at the Authorization Server’s Token Endpoint.
- [CAUTION]
- ====
- The `DefaultPasswordTokenResponseClient` class and support for the Resource Owner Password Credentials grant are deprecated.
- This section will be removed in Spring Security 7.
- ====
- The `DefaultPasswordTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request or post-handling of the Token Response.
- [[oauth2-client-password-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<OAuth2PasswordGrantRequest, RequestEntity<?>>`.
- 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].
- However, providing a custom `Converter` would let you extend the standard Token Request and add custom parameter(s).
- To customize only the parameters of the request, you can provide `OAuth2PasswordGrantRequestEntityConverter.setParametersConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>` to completely override the parameters sent with the request. This is often simpler than constructing a `RequestEntity` directly.
- [TIP]
- ====
- If you prefer to only add additional parameters, you can provide `OAuth2PasswordGrantRequestEntityConverter.addParametersConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>>` which constructs an aggregate `Converter`.
- ====
- [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.
- ====
- [[oauth2-client-password-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 need to provide `DefaultPasswordTokenResponseClient.setRestOperations()` with a custom configured `RestOperations`.
- The default `RestOperations` is configured as follows:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- RestTemplate restTemplate = new RestTemplate(Arrays.asList(
- new FormHttpMessageConverter(),
- new OAuth2AccessTokenResponseHttpMessageConverter()));
- restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- val restTemplate = RestTemplate(listOf(
- FormHttpMessageConverter(),
- OAuth2AccessTokenResponseHttpMessageConverter()))
- restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
- ----
- ======
- [TIP]
- ====
- Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request.
- ====
- `OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response.
- You can provide `OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter()` with a custom `Converter<Map<String, String>, OAuth2AccessTokenResponse>` that is used to convert the OAuth 2.0 Access Token Response parameters to an `OAuth2AccessTokenResponse`.
- `OAuth2ErrorResponseErrorHandler` is a `ResponseErrorHandler` that can handle an OAuth 2.0 Error, such as `400 Bad Request`.
- It uses an `OAuth2ErrorHttpMessageConverter` to convert the OAuth 2.0 Error parameters to an `OAuth2Error`.
- [[oauth2-client-password-authorized-client-provider-builder]]
- === Customize using the Builder
- Whether you customize `DefaultPasswordTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows:
- .Access Token Response Configuration via Builder
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- // Customize
- OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .password((configurer) -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
- .refreshToken()
- .build();
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .password { it.accessTokenResponseClient(passwordTokenResponseClient) }
- .refreshToken()
- .build()
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- ----
- ======
- [NOTE]
- ====
- `OAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordOAuth2AuthorizedClientProvider`,
- which is an implementation of an `OAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant.
- ====
- [[oauth2-client-password-authorized-client-manager]]
- === Using the Access Token
- Consider the following Spring Boot 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
- authorization-grant-type: password
- scope: read, write
- provider:
- okta:
- token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
- ----
- Further consider the `OAuth2AuthorizedClientManager` `@Bean`:
- [tabs]
- ======
- 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<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
- return authorizeRequest -> {
- Map<String, Object> contextAttributes = Collections.emptyMap();
- HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
- String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
- String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
- if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
- contextAttributes = new HashMap<>();
- // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
- contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
- contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
- }
- return contextAttributes;
- };
- }
- ----
- 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<OAuth2AuthorizeRequest, MutableMap<String, Any>> {
- return Function { authorizeRequest ->
- var contextAttributes: MutableMap<String, Any> = mutableMapOf()
- val servletRequest: HttpServletRequest = authorizeRequest.getAttribute(HttpServletRequest::class.java.name)
- val username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME)
- val password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD)
- if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
- contextAttributes = hashMapOf()
- // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
- contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
- contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
- }
- contextAttributes
- }
- }
- ----
- ======
- Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Controller
- public class OAuth2ClientController {
- @Autowired
- private OAuth2AuthorizedClientManager authorizedClientManager;
- @GetMapping("/")
- public String index(Authentication authentication,
- HttpServletRequest servletRequest,
- HttpServletResponse servletResponse) {
- OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(authentication)
- .attributes(attrs -> {
- attrs.put(HttpServletRequest.class.getName(), servletRequest);
- attrs.put(HttpServletResponse.class.getName(), servletResponse);
- })
- .build();
- OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
- OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
- // ...
- return "index";
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Controller
- class OAuth2ClientController {
- @Autowired
- private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
- @GetMapping("/")
- fun index(authentication: Authentication?,
- servletRequest: HttpServletRequest,
- servletResponse: HttpServletResponse): String {
- val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(authentication)
- .attributes(Consumer {
- it[HttpServletRequest::class.java.name] = servletRequest
- it[HttpServletResponse::class.java.name] = servletResponse
- })
- .build()
- val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
- val accessToken: OAuth2AccessToken = authorizedClient.accessToken
- // ...
- return "index"
- }
- }
- ----
- ======
- [NOTE]
- ====
- `HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes.
- If not provided, they default to `ServletRequestAttributes` using `RequestContextHolder.getRequestAttributes()`.
- ====
- [[oauth2-client-jwt-bearer]]
- == [[oauth2Client-jwt-bearer-grant]]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.
- ====
- [[oauth2-client-jwt-bearer-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.
- ====
- There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the JWT Bearer grant:
- * `DefaultJwtBearerTokenResponseClient` (_default_)
- * `RestClientJwtBearerTokenResponseClient`
- The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
- Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
- [NOTE]
- ====
- This section focuses on `RestClientJwtBearerTokenResponseClient`.
- You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token_4[`DefaultClientCredentialsTokenResponseClient`] in the Spring Security 6.3 documentation.
- ====
- :section-id: jwt-bearer
- :grant-type: JWT Bearer
- :class-name: RestClientJwtBearerTokenResponseClient
- :grant-request: JwtBearerGrantRequest
- :leveloffset: +1
- include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
- :leveloffset: -1
- [[oauth2-client-jwt-bearer-authorized-client-provider-builder]]
- === Customize using the Builder
- Whether you customize `RestClientJwtBearerTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-jwt-bearer-access-token-response-client-bean,publishing a bean>>) as follows:
- .Access Token Response Configuration via Builder
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- // Customize
- OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
- JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
- jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(jwtBearerAuthorizedClientProvider)
- .build();
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- // Customize
- val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
- val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
- jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(jwtBearerAuthorizedClientProvider)
- .build()
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- ----
- ======
- [[oauth2-client-jwt-bearer-authorized-client-manager]]
- === Using the Access Token
- Given the following Spring Boot 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
- authorization-grant-type: urn:ietf:params:oauth:grant-type:jwt-bearer
- scope: read
- provider:
- okta:
- token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
- ----
- ...and the `OAuth2AuthorizedClientManager` `@Bean`:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Bean
- public OAuth2AuthorizedClientManager authorizedClientManager(
- ClientRegistrationRepository clientRegistrationRepository,
- OAuth2AuthorizedClientRepository authorizedClientRepository) {
- JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider =
- new JwtBearerOAuth2AuthorizedClientProvider();
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(jwtBearerAuthorizedClientProvider)
- .build();
- DefaultOAuth2AuthorizedClientManager authorizedClientManager =
- new DefaultOAuth2AuthorizedClientManager(
- clientRegistrationRepository, authorizedClientRepository);
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- return authorizedClientManager;
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun authorizedClientManager(
- clientRegistrationRepository: ClientRegistrationRepository,
- authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
- val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(jwtBearerAuthorizedClientProvider)
- .build()
- val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
- clientRegistrationRepository, authorizedClientRepository)
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- return authorizedClientManager
- }
- ----
- ======
- You may obtain the `OAuth2AccessToken` as follows:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @RestController
- public class OAuth2ResourceServerController {
- @Autowired
- private OAuth2AuthorizedClientManager authorizedClientManager;
- @GetMapping("/resource")
- public String resource(JwtAuthenticationToken jwtAuthentication) {
- OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(jwtAuthentication)
- .build();
- OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
- OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
- // ...
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- class OAuth2ResourceServerController {
- @Autowired
- private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
- @GetMapping("/resource")
- fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
- val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(jwtAuthentication)
- .build()
- val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
- val accessToken: OAuth2AccessToken = authorizedClient.accessToken
- // ...
- }
- }
- ----
- ======
- [NOTE]
- ====
- `JwtBearerOAuth2AuthorizedClientProvider` resolves the `Jwt` assertion via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
- ====
- [TIP]
- ====
- If you need to resolve the `Jwt` assertion from a different source, you can provide `JwtBearerOAuth2AuthorizedClientProvider.setJwtAssertionResolver()` with a custom `Function<OAuth2AuthorizationContext, Jwt>`.
- ====
- [[oauth2-client-token-exchange]]
- == [[oauth2Client-token-exchange-grant]]Token Exchange
- [NOTE]
- ====
- Please refer to OAuth 2.0 Token Exchange for further details on the https://datatracker.ietf.org/doc/html/rfc8693[Token Exchange] grant.
- ====
- [[oauth2-client-token-exchange-access-token]]
- === Requesting an Access Token
- [NOTE]
- ====
- Please refer to the https://datatracker.ietf.org/doc/html/rfc8693#section-2[Token Exchange Request and Response] protocol flow for the Token Exchange grant.
- ====
- There are two implementations of `OAuth2AccessTokenResponseClient` that can be used to make HTTP requests to the Token Endpoint in order to obtain an access token for the Token Exchange grant:
- * `DefaultTokenExchangeTokenResponseClient` (_default_)
- * `RestClientTokenExchangeTokenResponseClient`
- The default implementation uses a `RestOperations` instance to exchange an authorization code for an access token at the Authorization Server’s Token Endpoint.
- Spring Security 6.4 introduces a new implementation based on `RestClient`, which provides similar functionality but is better aligned with the Reactive version of the component (based on `WebClient`) in order to provide consistent configuration for applications on either stack.
- [NOTE]
- ====
- This section focuses on `RestClientTokenExchangeTokenResponseClient`.
- You can read about {spring-security-reference-base-url}/6.3/servlet/oauth2/client/authorization-grants.html#_requesting_an_access_token_5[`DefaultTokenExchangeTokenResponseClient`] in the Spring Security 6.3 documentation.
- ====
- :section-id: token-exchange
- :grant-type: Token Exchange
- :class-name: RestClientTokenExchangeTokenResponseClient
- :grant-request: TokenExchangeGrantRequest
- :leveloffset: +1
- include::partial$servlet/oauth2/client/rest-client-access-token-response-client.adoc[]
- :leveloffset: -1
- [[oauth2-client-token-exchange-authorized-client-provider-builder]]
- === Customize using the Builder
- Whether you customize `RestClientTokenExchangeTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you can configure it using the `OAuth2AuthorizedClientProviderBuilder` (as an alternative to <<oauth2-client-token-exchange-access-token-response-client-bean,publishing a bean>>) as follows:
- .Access Token Response Configuration via Builder
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- // Customize
- OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeTokenResponseClient = ...
- TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider = new TokenExchangeOAuth2AuthorizedClientProvider();
- tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient);
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(tokenExchangeAuthorizedClientProvider)
- .build();
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- // Customize
- val tokenExchangeTokenResponseClient: OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> = ...
- val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
- tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient)
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(tokenExchangeAuthorizedClientProvider)
- .build()
- // ...
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- ----
- ======
- [[oauth2-client-token-exchange-authorized-client-manager]]
- === [[token-exchange-grant-access-token]]Using the Access Token
- Given the following Spring Boot 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
- authorization-grant-type: urn:ietf:params:oauth:grant-type:token-exchange
- scope: read
- provider:
- okta:
- token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
- ----
- ...and the `OAuth2AuthorizedClientManager` `@Bean`:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @Bean
- public OAuth2AuthorizedClientManager authorizedClientManager(
- ClientRegistrationRepository clientRegistrationRepository,
- OAuth2AuthorizedClientRepository authorizedClientRepository) {
- TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
- new TokenExchangeOAuth2AuthorizedClientProvider();
- OAuth2AuthorizedClientProvider authorizedClientProvider =
- OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(tokenExchangeAuthorizedClientProvider)
- .build();
- DefaultOAuth2AuthorizedClientManager authorizedClientManager =
- new DefaultOAuth2AuthorizedClientManager(
- clientRegistrationRepository, authorizedClientRepository);
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
- return authorizedClientManager;
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun authorizedClientManager(
- clientRegistrationRepository: ClientRegistrationRepository,
- authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
- val tokenExchangeAuthorizedClientProvider = TokenExchangeOAuth2AuthorizedClientProvider()
- val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
- .provider(tokenExchangeAuthorizedClientProvider)
- .build()
- val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
- clientRegistrationRepository, authorizedClientRepository)
- authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
- return authorizedClientManager
- }
- ----
- ======
- You may obtain the `OAuth2AccessToken` as follows:
- [tabs]
- ======
- Java::
- +
- [source,java,role="primary"]
- ----
- @RestController
- public class OAuth2ResourceServerController {
- @Autowired
- private OAuth2AuthorizedClientManager authorizedClientManager;
- @GetMapping("/resource")
- public String resource(JwtAuthenticationToken jwtAuthentication) {
- OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(jwtAuthentication)
- .build();
- OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
- OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
- // ...
- }
- }
- ----
- Kotlin::
- +
- [source,kotlin,role="secondary"]
- ----
- class OAuth2ResourceServerController {
- @Autowired
- private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
- @GetMapping("/resource")
- fun resource(jwtAuthentication: JwtAuthenticationToken?): String {
- val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
- .principal(jwtAuthentication)
- .build()
- val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
- val accessToken: OAuth2AccessToken = authorizedClient.accessToken
- // ...
- }
- }
- ----
- ======
- [NOTE]
- ====
- `TokenExchangeOAuth2AuthorizedClientProvider` resolves the subject token (as an `OAuth2Token`) via `OAuth2AuthorizationContext.getPrincipal().getPrincipal()` by default, hence the use of `JwtAuthenticationToken` in the preceding example.
- An actor token is not resolved by default.
- ====
- [TIP]
- ====
- If you need to resolve the subject token from a different source, you can provide `TokenExchangeOAuth2AuthorizedClientProvider.setSubjectTokenResolver()` with a custom `Function<OAuth2AuthorizationContext, OAuth2Token>`.
- ====
- [TIP]
- ====
- If you need to resolve an actor token, you can provide `TokenExchangeOAuth2AuthorizedClientProvider.setActorTokenResolver()` with a custom `Function<OAuth2AuthorizationContext, OAuth2Token>`.
- ====
|