2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-grants]]
= [[oauth2Client-auth-grant-support]]Authorization Grant Support
:spring-security-reference-base-url: https://docs.spring.io/spring-security/reference
2018-10-11 04:56:09 +08:00
2021-04-22 05:01:26 +08:00
This section describes Spring Security's support for authorization grants.
2018-10-11 04:56:09 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code]]
== [[oauth2Client-auth-code-grant]]Authorization Code
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
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.
====
2019-09-12 18:43:39 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code-authorization]]
2021-11-05 01:31:27 +08:00
=== Obtaining Authorization
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
See the https://tools.ietf.org/html/rfc6749#section-4.1.1[Authorization Request/Response] protocol flow for the Authorization Code grant.
====
2018-10-11 04:56:09 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code-authorization-request]]
2021-11-05 01:31:27 +08:00
=== Initiating the Authorization Request
2020-03-04 11:24:14 +08:00
2021-11-05 01:31:27 +08:00
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.
2020-03-04 11:24:14 +08:00
2021-11-05 01:31:27 +08:00
The primary role of the `OAuth2AuthorizationRequestResolver` is to resolve an `OAuth2AuthorizationRequest` from the provided web request.
2021-04-22 05:01:26 +08:00
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`.
2020-03-17 22:08:09 +08:00
2024-03-27 04:22:24 +08:00
Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
2020-03-17 22:08:09 +08:00
2021-11-05 01:31:27 +08:00
[source,yaml,attrs="-attributes"]
2020-03-17 22:08:09 +08:00
----
2021-11-05 01:31:27 +08:00
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
2019-09-12 18:43:39 +08:00
----
2021-04-22 05:01:26 +08:00
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.
2019-09-12 18:43:39 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
The `AuthorizationCodeOAuth2AuthorizedClientProvider` is an implementation of `OAuth2AuthorizedClientProvider` for the Authorization Code grant,
which also initiates the Authorization Request redirect by the `OAuth2AuthorizationRequestRedirectFilter`.
2021-06-05 03:12:59 +08:00
====
2019-09-12 18:43:39 +08:00
2021-04-22 05:01:26 +08:00
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:
2019-09-12 18:43:39 +08:00
2021-11-05 01:31:27 +08:00
[source,yaml,attrs="-attributes"]
2020-08-11 20:07:35 +08:00
----
2021-11-05 01:31:27 +08:00
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"
2024-10-17 23:50:59 +08:00
# ...
2020-08-11 20:07:35 +08:00
----
2021-04-22 05:01:26 +08:00
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:
2021-11-05 01:31:27 +08:00
. `client-secret` is omitted (or empty)
2021-12-14 06:57:36 +08:00
. `client-authentication-method` is set to `none` (`ClientAuthenticationMethod.NONE`)
2018-10-11 04:56:09 +08:00
2022-03-15 22:25:17 +08:00
[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())`.
2024-10-17 23:50:59 +08:00
[[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`.
2019-09-21 00:53:53 +08:00
2021-11-05 01:31:27 +08:00
The following configuration uses all the supported `URI` template variables:
2019-09-21 00:53:53 +08:00
2021-11-05 01:31:27 +08:00
[source,yaml,attrs="-attributes"]
2020-08-11 20:07:35 +08:00
----
2021-11-05 01:31:27 +08:00
spring:
security:
oauth2:
client:
registration:
okta:
2024-10-17 23:50:59 +08:00
# ...
2021-11-05 01:31:27 +08:00
redirect-uri: "{baseScheme}://{baseHost}{basePort}{basePath}/authorized/{registrationId}"
2024-10-17 23:50:59 +08:00
# ...
2020-08-11 20:07:35 +08:00
----
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
`+{baseUrl}+` resolves to `+{baseScheme}://{baseHost}{basePort}{basePath}+`
2021-06-05 03:12:59 +08:00
====
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
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].
2021-04-22 05:01:26 +08:00
Doing so ensures that the `X-Forwarded-*` headers are used when expanding the `redirect-uri`.
2018-10-11 04:56:09 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code-authorization-request-resolver]]
2021-11-05 01:31:27 +08:00
=== Customizing the Authorization Request
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
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.
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
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.
2018-10-11 04:56:09 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
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`.
====
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
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`.
2018-10-11 04:56:09 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2018-10-11 04:56:09 +08:00
----
2022-07-30 09:47:02 +08:00
@Configuration
2021-11-05 01:31:27 +08:00
@EnableWebSecurity
2022-02-08 23:12:10 +08:00
public class OAuth2LoginSecurityConfig {
2018-10-11 04:56:09 +08:00
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
2022-02-08 23:12:10 +08:00
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
2021-11-05 01:31:27 +08:00
http
2021-11-11 06:15:11 +08:00
.authorizeHttpRequests(authorize -> authorize
2021-11-05 01:31:27 +08:00
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.authorizationEndpoint(authorization -> authorization
.authorizationRequestResolver(
authorizationRequestResolver(this.clientRegistrationRepository)
)
)
);
2022-02-08 23:12:10 +08:00
return http.build();
2021-11-05 01:31:27 +08:00
}
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
private OAuth2AuthorizationRequestResolver authorizationRequestResolver(
ClientRegistrationRepository clientRegistrationRepository) {
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
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"));
2018-10-11 04:56:09 +08:00
}
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
2022-07-30 09:47:02 +08:00
@Configuration
2021-11-05 01:31:27 +08:00
@EnableWebSecurity
2022-02-08 23:12:10 +08:00
class SecurityConfig {
2020-08-11 20:07:35 +08:00
@Autowired
2021-11-05 01:31:27 +08:00
private lateinit var customClientRegistrationRepository: ClientRegistrationRepository
2020-08-11 20:07:35 +08:00
2022-02-08 23:12:10 +08:00
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
2021-11-05 01:31:27 +08:00
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
oauth2Login {
authorizationEndpoint {
authorizationRequestResolver = authorizationRequestResolver(customClientRegistrationRepository)
}
}
}
2022-02-08 23:12:10 +08:00
return http.build()
2021-11-05 01:31:27 +08:00
}
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
private fun authorizationRequestResolver(
2024-10-17 23:50:59 +08:00
clientRegistrationRepository: ClientRegistrationRepository?): OAuth2AuthorizationRequestResolver {
2021-11-05 01:31:27 +08:00
val authorizationRequestResolver = DefaultOAuth2AuthorizationRequestResolver(
clientRegistrationRepository, "/oauth2/authorization")
authorizationRequestResolver.setAuthorizationRequestCustomizer(
authorizationRequestCustomizer())
return authorizationRequestResolver
}
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
return Consumer { customizer ->
customizer
.additionalParameters { params -> params["prompt"] = "consent" }
}
2020-08-11 20:07:35 +08:00
}
}
----
2023-06-19 10:30:41 +08:00
======
2018-10-11 04:56:09 +08:00
2021-04-22 05:01:26 +08:00
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.
2018-10-11 04:56:09 +08:00
2021-04-22 05:01:26 +08:00
For example, if the value for the request parameter `prompt` is always `consent` for the provider `okta`, you can configure it as follows:
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
[source,yaml]
----
spring:
security:
oauth2:
client:
provider:
okta:
authorization-uri: https://dev-1234.oktapreview.com/oauth2/v1/authorize?prompt=consent
----
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
2021-04-22 05:01:26 +08:00
Alternatively, if your requirements are more advanced, you can take full control in building the Authorization Request URI by overriding the `OAuth2AuthorizationRequest.authorizationRequestUri` property.
2018-10-11 04:56:09 +08:00
2021-11-05 01:31:27 +08:00
[TIP]
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
`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.
2021-06-05 03:12:59 +08:00
====
2018-10-11 04:56:09 +08:00
2021-04-22 05:01:26 +08:00
The following example shows a variation of `authorizationRequestCustomizer()` from the preceding example and instead overrides the `OAuth2AuthorizationRequest.authorizationRequestUri` property:
2018-10-11 04:56:09 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2018-10-11 04:56:09 +08:00
----
2021-11-05 01:31:27 +08:00
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer() {
return customizer -> customizer
.authorizationRequestUri(uriBuilder -> uriBuilder
.queryParam("prompt", "consent").build());
2018-10-11 04:56:09 +08:00
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
2021-11-05 01:31:27 +08:00
private fun authorizationRequestCustomizer(): Consumer<OAuth2AuthorizationRequest.Builder> {
return Consumer { customizer: OAuth2AuthorizationRequest.Builder ->
customizer
.authorizationRequestUri { uriBuilder: UriBuilder ->
uriBuilder
.queryParam("prompt", "consent").build()
}
2020-08-11 20:07:35 +08:00
}
}
----
2023-06-19 10:30:41 +08:00
======
2020-08-11 20:07:35 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code-authorization-request-repository]]
2021-11-05 01:31:27 +08:00
=== Storing the Authorization Request
2019-09-12 03:49:56 +08:00
2021-11-05 01:31:27 +08:00
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).
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
[TIP]
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
The `OAuth2AuthorizationRequest` is used to correlate and validate the Authorization Response.
2021-06-05 03:12:59 +08:00
====
2020-03-20 23:58:20 +08:00
2021-11-05 01:31:27 +08:00
The default implementation of `AuthorizationRequestRepository` is `HttpSessionOAuth2AuthorizationRequestRepository`, which stores the `OAuth2AuthorizationRequest` in the `HttpSession`.
2019-09-20 03:33:23 +08:00
2021-04-22 05:01:26 +08:00
If you have a custom implementation of `AuthorizationRequestRepository`, you can configure it as follows:
2019-09-20 03:33:23 +08:00
2021-11-05 01:31:27 +08:00
.AuthorizationRequestRepository Configuration
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2019-09-20 03:33:23 +08:00
----
2022-07-30 09:47:02 +08:00
@Configuration
2021-11-05 01:31:27 +08:00
@EnableWebSecurity
2022-02-08 23:12:10 +08:00
public class OAuth2ClientSecurityConfig {
2019-09-20 03:33:23 +08:00
2022-02-08 23:12:10 +08:00
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
2021-11-05 01:31:27 +08:00
http
.oauth2Client(oauth2 -> oauth2
.authorizationCodeGrant(codeGrant -> codeGrant
.authorizationRequestRepository(this.authorizationRequestRepository())
2024-10-17 23:50:59 +08:00
// ...
2021-11-05 01:31:27 +08:00
)
2024-10-17 23:50:59 +08:00
)
2023-04-26 10:54:43 +08:00
.oauth2Login(oauth2 -> oauth2
.authorizationEndpoint(endpoint -> endpoint
.authorizationRequestRepository(this.authorizationRequestRepository())
2024-10-17 23:50:59 +08:00
// ...
2023-04-26 10:54:43 +08:00
)
2024-10-17 23:50:59 +08:00
);
return http.build();
2021-11-05 01:31:27 +08:00
}
2023-04-26 10:54:43 +08:00
@Bean
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
return new CustomOAuth2AuthorizationRequestRepository();
}
2019-09-20 03:33:23 +08:00
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
2022-07-30 09:47:02 +08:00
@Configuration
2021-11-05 01:31:27 +08:00
@EnableWebSecurity
2022-02-08 23:12:10 +08:00
class OAuth2ClientSecurityConfig {
2020-08-11 20:07:35 +08:00
2022-02-08 23:12:10 +08:00
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
2021-11-05 01:31:27 +08:00
http {
oauth2Client {
authorizationCodeGrant {
authorizationRequestRepository = authorizationRequestRepository()
}
}
2020-08-11 20:07:35 +08:00
}
2022-02-08 23:12:10 +08:00
return http.build()
2020-08-11 20:07:35 +08:00
}
}
----
2018-10-11 04:56:09 +08:00
2023-06-19 10:30:41 +08:00
Xml::
+
2021-11-05 01:31:27 +08:00
[source,xml,role="secondary"]
2020-03-17 22:08:09 +08:00
----
<http>
<oauth2-client>
<authorization-code-grant authorization-request-repository-ref="authorizationRequestRepository"/>
</oauth2-client>
</http>
----
2023-06-19 10:30:41 +08:00
======
2019-09-12 18:43:39 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code-access-token]]
2021-11-05 01:31:27 +08:00
=== Requesting an Access Token
2019-09-19 19:12:08 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
See the https://tools.ietf.org/html/rfc6749#section-4.1.3[Access Token Request/Response] protocol flow for the Authorization Code grant.
====
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
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:
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
* `DefaultAuthorizationCodeTokenResponseClient` (_default_)
* `RestClientAuthorizationCodeTokenResponseClient`
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
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.
2021-11-04 06:01:37 +08:00
2024-10-17 23:50:59 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2024-10-17 23:50:59 +08:00
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.
2021-12-14 06:57:36 +08:00
====
2021-11-04 06:01:37 +08:00
2024-10-17 23:50:59 +08:00
: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[]
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
:leveloffset: -1
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-authorization-code-access-token-response-client-dsl]]
=== Customize using the DSL
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
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:
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
.Access Token Response Configuration via DSL
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2019-09-19 19:12:08 +08:00
----
2022-07-30 09:47:02 +08:00
@Configuration
2021-11-05 01:31:27 +08:00
@EnableWebSecurity
2022-02-08 23:12:10 +08:00
public class OAuth2ClientSecurityConfig {
2019-09-19 19:12:08 +08:00
2022-02-08 23:12:10 +08:00
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
2021-11-05 01:31:27 +08:00
http
.oauth2Client(oauth2 -> oauth2
.authorizationCodeGrant(codeGrant -> codeGrant
.accessTokenResponseClient(this.accessTokenResponseClient())
2024-10-17 23:50:59 +08:00
// ...
2021-11-05 01:31:27 +08:00
)
);
2022-02-08 23:12:10 +08:00
return http.build();
2021-11-05 01:31:27 +08:00
}
}
2019-09-19 19:12:08 +08:00
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
2022-07-30 09:47:02 +08:00
@Configuration
2021-11-05 01:31:27 +08:00
@EnableWebSecurity
2022-02-08 23:12:10 +08:00
class OAuth2ClientSecurityConfig {
2020-08-11 20:07:35 +08:00
2022-02-08 23:12:10 +08:00
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
2021-11-05 01:31:27 +08:00
http {
oauth2Client {
authorizationCodeGrant {
accessTokenResponseClient = accessTokenResponseClient()
}
}
}
2022-02-08 23:12:10 +08:00
return http.build()
2021-11-05 01:31:27 +08:00
}
}
----
2020-08-11 20:07:35 +08:00
2023-06-19 10:30:41 +08:00
Xml::
+
2021-11-05 01:31:27 +08:00
[source,xml,role="secondary"]
----
<http>
<oauth2-client>
<authorization-code-grant access-token-response-client-ref="accessTokenResponseClient"/>
</oauth2-client>
</http>
2020-08-11 20:07:35 +08:00
----
2023-06-19 10:30:41 +08:00
======
2020-08-11 20:07:35 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-refresh-token]]
== [[oauth2Client-refresh-token-grant]]Refresh Token
2021-11-05 01:31:27 +08:00
2019-09-19 19:12:08 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.5[Refresh Token].
====
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-refresh-token-access-token]]
2021-11-05 01:31:27 +08:00
=== Refreshing an Access Token
2019-09-19 19:12:08 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
See the https://tools.ietf.org/html/rfc6749#section-6[Access Token Request/Response] protocol flow for the Refresh Token grant.
====
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
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:
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
* `DefaultRefreshTokenTokenResponseClient` (_default_)
* `RestClientRefreshTokenTokenResponseClient`
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
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.
2019-09-19 19:12:08 +08:00
2024-10-17 23:50:59 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2024-10-17 23:50:59 +08:00
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.
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
: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[]
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
:leveloffset: -1
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-refresh-token-authorized-client-provider-builder]]
=== Customize using the Builder
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
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:
2019-09-19 19:12:08 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2019-09-16 08:08:51 +08:00
----
2021-11-05 01:31:27 +08:00
// Customize
OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient = ...
2019-09-16 08:08:51 +08:00
2021-11-05 01:31:27 +08:00
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken(configurer -> configurer.accessTokenResponseClient(refreshTokenTokenResponseClient))
2019-09-16 08:08:51 +08:00
.build();
2024-10-17 23:50:59 +08:00
// ...
2019-09-16 08:08:51 +08:00
2021-11-05 01:31:27 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
2019-09-16 08:08:51 +08:00
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-11-05 01:31:27 +08:00
[source,kotlin,role="secondary"]
----
// Customize
val refreshTokenTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> = ...
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken { it.accessTokenResponseClient(refreshTokenTokenResponseClient) }
.build()
2020-08-11 20:07:35 +08:00
2024-10-17 23:50:59 +08:00
// ...
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
2020-08-11 20:07:35 +08:00
----
2023-06-19 10:30:41 +08:00
======
2020-08-11 20:07:35 +08:00
2019-09-16 08:08:51 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
`OAuth2AuthorizedClientProviderBuilder.builder().refreshToken()` configures a `RefreshTokenOAuth2AuthorizedClientProvider`,
which is an implementation of an `OAuth2AuthorizedClientProvider` for the Refresh Token grant.
2021-12-14 06:57:36 +08:00
====
2019-09-16 08:08:51 +08:00
2021-04-22 05:01:26 +08:00
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`.
2019-09-16 08:08:51 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-client-credentials]]
== [[oauth2Client-client-creds-grant]]Client Credentials
2021-05-14 22:17:20 +08:00
[NOTE]
2024-10-17 23:50:59 +08:00
====
2021-11-05 01:31:27 +08:00
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.
2024-10-17 23:50:59 +08:00
====
2021-05-14 22:17:20 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-client-credentials-access-token]]
2021-11-05 01:31:27 +08:00
=== Requesting an Access Token
2021-05-14 22:17:20 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2021-12-14 06:57:36 +08:00
See the OAuth 2.0 Authorization Framework for further details on the https://tools.ietf.org/html/rfc6749#section-1.3.4[Client Credentials] grant.
2021-06-05 03:12:59 +08:00
====
2021-05-14 22:17:20 +08:00
2024-10-17 23:50:59 +08:00
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:
2021-05-14 22:17:20 +08:00
2024-10-17 23:50:59 +08:00
* `DefaultClientCredentialsTokenResponseClient` (_default_)
* `RestClientClientCredentialsTokenResponseClient`
2021-05-14 22:17:20 +08:00
2024-10-17 23:50:59 +08:00
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.
2021-11-04 06:01:37 +08:00
2024-10-17 23:50:59 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2024-10-17 23:50:59 +08:00
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.
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
: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[]
2021-11-04 06:01:37 +08:00
2024-10-17 23:50:59 +08:00
:leveloffset: -1
2021-05-14 22:17:20 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-client-credentials-authorized-client-provider-builder]]
=== Customize using the Builder
2021-05-14 22:17:20 +08:00
2024-10-17 23:50:59 +08:00
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:
2021-05-14 22:17:20 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-05-14 22:17:20 +08:00
[source,java,role="primary"]
----
// Customize
2021-11-05 01:31:27 +08:00
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = ...
2021-05-14 22:17:20 +08:00
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
2021-11-05 01:31:27 +08:00
.clientCredentials(configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
2021-05-14 22:17:20 +08:00
.build();
2024-10-17 23:50:59 +08:00
// ...
2021-05-14 22:17:20 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-05-14 22:17:20 +08:00
[source,kotlin,role="secondary"]
----
// Customize
2021-11-05 01:31:27 +08:00
val clientCredentialsTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> = ...
2021-05-14 22:17:20 +08:00
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
2021-11-05 01:31:27 +08:00
.clientCredentials { it.accessTokenResponseClient(clientCredentialsTokenResponseClient) }
2021-05-14 22:17:20 +08:00
.build()
2024-10-17 23:50:59 +08:00
// ...
2021-05-14 22:17:20 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
----
2023-06-19 10:30:41 +08:00
======
2021-05-14 22:17:20 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
`OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials()` configures a `ClientCredentialsOAuth2AuthorizedClientProvider`,
which is an implementation of an `OAuth2AuthorizedClientProvider` for the Client Credentials grant.
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-client-credentials-authorized-client-manager]]
2021-11-05 01:31:27 +08:00
=== Using the Access Token
2021-05-14 22:17:20 +08:00
2024-03-27 04:22:24 +08:00
Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
2021-05-14 22:17:20 +08:00
[source,yaml]
----
spring:
security:
oauth2:
client:
registration:
okta:
client-id: okta-client-id
client-secret: okta-client-secret
2021-11-05 01:31:27 +08:00
authorization-grant-type: client_credentials
scope: read, write
2021-05-14 22:17:20 +08:00
provider:
okta:
token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
----
2021-04-22 05:01:26 +08:00
Further consider the following `OAuth2AuthorizedClientManager` `@Bean`:
2021-05-14 22:17:20 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-05-14 22:17:20 +08:00
[source,java,role="primary"]
----
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
2021-11-05 01:31:27 +08:00
.clientCredentials()
2021-05-14 22:17:20 +08:00
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-05-14 22:17:20 +08:00
[source,kotlin,role="secondary"]
----
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
2021-11-05 01:31:27 +08:00
.clientCredentials()
2021-05-14 22:17:20 +08:00
.build()
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
}
----
2023-06-19 10:30:41 +08:00
======
2021-05-14 22:17:20 +08:00
2021-04-22 05:01:26 +08:00
Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows:
2021-05-14 22:17:20 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-05-14 22:17:20 +08:00
[source,java,role="primary"]
----
2021-11-05 01:31:27 +08:00
@Controller
public class OAuth2ClientController {
2021-05-14 22:17:20 +08:00
@Autowired
private OAuth2AuthorizedClientManager authorizedClientManager;
2021-11-05 01:31:27 +08:00
@GetMapping("/")
public String index(Authentication authentication,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
2021-05-14 22:17:20 +08:00
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
2021-11-05 01:31:27 +08:00
.principal(authentication)
.attributes(attrs -> {
attrs.put(HttpServletRequest.class.getName(), servletRequest);
attrs.put(HttpServletResponse.class.getName(), servletResponse);
})
2021-05-14 22:17:20 +08:00
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
2021-11-05 01:31:27 +08:00
2021-05-14 22:17:20 +08:00
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
2024-10-17 23:50:59 +08:00
// ...
2021-05-14 22:17:20 +08:00
2021-11-05 01:31:27 +08:00
return "index";
2021-05-14 22:17:20 +08:00
}
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-05-14 22:17:20 +08:00
[source,kotlin,role="secondary"]
----
2021-11-05 01:31:27 +08:00
class OAuth2ClientController {
2021-05-14 22:17:20 +08:00
@Autowired
private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
2021-11-05 01:31:27 +08:00
@GetMapping("/")
fun index(authentication: Authentication?,
servletRequest: HttpServletRequest,
servletResponse: HttpServletResponse): String {
2021-05-14 22:17:20 +08:00
val authorizeRequest: OAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("okta")
2021-11-05 01:31:27 +08:00
.principal(authentication)
.attributes(Consumer { attrs: MutableMap<String, Any> ->
attrs[HttpServletRequest::class.java.name] = servletRequest
attrs[HttpServletResponse::class.java.name] = servletResponse
})
2021-05-14 22:17:20 +08:00
.build()
val authorizedClient = authorizedClientManager.authorize(authorizeRequest)
val accessToken: OAuth2AccessToken = authorizedClient.accessToken
2024-10-17 23:50:59 +08:00
// ...
2021-05-14 22:17:20 +08:00
2021-11-05 01:31:27 +08:00
return "index"
2021-05-14 22:17:20 +08:00
}
}
----
2023-06-19 10:30:41 +08:00
======
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
`HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes.
2021-04-22 05:01:26 +08:00
If not provided, they default to `ServletRequestAttributes` by using `RequestContextHolder.getRequestAttributes()`.
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-password]]
== [[oauth2Client-password-grant]]Resource Owner Password Credentials
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
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.
====
2021-05-15 10:04:28 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-password-access-token]]
2021-11-05 01:31:27 +08:00
=== Requesting an Access Token
2021-05-15 10:04:28 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
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.
====
2021-11-05 01:31:27 +08:00
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.
2021-05-15 10:04:28 +08:00
2024-10-17 23:50:59 +08:00
[CAUTION]
====
The `DefaultPasswordTokenResponseClient` class and support for the Resource Owner Password Credentials grant are deprecated.
This section will be removed in Spring Security 7.
====
2021-04-22 05:01:26 +08:00
The `DefaultPasswordTokenResponseClient` is flexible, as it lets you customize the pre-processing of the Token Request or post-handling of the Token Response.
2021-05-15 10:04:28 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-password-access-token-request]]
2021-11-05 01:31:27 +08:00
=== Customizing the Access Token Request
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
If you need to customize the pre-processing of the Token Request, you can provide `DefaultPasswordTokenResponseClient.setRequestEntityConverter()` with a custom `Converter<OAuth2PasswordGrantRequest, RequestEntity<?>>`.
2021-04-22 05:01:26 +08:00
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).
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
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.
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
[TIP]
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
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`.
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
2021-06-05 03:12:59 +08:00
[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.
====
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-password-access-token-response]]
2021-11-05 01:31:27 +08:00
=== Customizing the Access Token Response
2021-04-22 05:01:26 +08:00
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`.
2021-11-05 01:31:27 +08:00
The default `RestOperations` is configured as follows:
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-11-05 01:31:27 +08:00
[source,java,role="primary"]
2021-05-15 10:04:28 +08:00
----
2021-11-05 01:31:27 +08:00
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-11-05 01:31:27 +08:00
[source,kotlin,role="secondary"]
----
val restTemplate = RestTemplate(listOf(
FormHttpMessageConverter(),
OAuth2AccessTokenResponseHttpMessageConverter()))
restTemplate.errorHandler = OAuth2ErrorResponseErrorHandler()
2021-05-15 10:04:28 +08:00
----
2023-06-19 10:30:41 +08:00
======
2021-11-05 01:31:27 +08:00
2021-06-05 03:12:59 +08:00
[TIP]
====
Spring MVC `FormHttpMessageConverter` is required, as it is used when sending the OAuth 2.0 Access Token Request.
====
2021-11-05 01:31:27 +08:00
`OAuth2AccessTokenResponseHttpMessageConverter` is a `HttpMessageConverter` for an OAuth 2.0 Access Token Response.
2021-04-22 05:01:26 +08:00
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`.
2021-11-05 01:31:27 +08:00
2021-04-22 05:01:26 +08:00
`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`.
2021-05-15 10:04:28 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-password-authorized-client-provider-builder]]
=== Customize using the Builder
2021-04-22 05:01:26 +08:00
Whether you customize `DefaultPasswordTokenResponseClient` or provide your own implementation of `OAuth2AccessTokenResponseClient`, you need to configure it as follows:
2021-05-15 10:04:28 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-05-15 10:04:28 +08:00
[source,java,role="primary"]
----
2021-11-05 01:31:27 +08:00
// Customize
OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = ...
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.password(configurer -> configurer.accessTokenResponseClient(passwordTokenResponseClient))
.refreshToken()
2021-05-15 10:04:28 +08:00
.build();
2024-10-17 23:50:59 +08:00
// ...
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
2021-05-15 10:04:28 +08:00
----
2021-05-17 16:33:42 +08:00
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-05-17 16:33:42 +08:00
[source,kotlin,role="secondary"]
----
2021-11-05 01:31:27 +08:00
val passwordTokenResponseClient: OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> = ...
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.password { it.accessTokenResponseClient(passwordTokenResponseClient) }
.refreshToken()
.build()
2021-05-17 16:33:42 +08:00
2024-10-17 23:50:59 +08:00
// ...
2021-05-17 16:33:42 +08:00
2021-11-05 01:31:27 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
2021-05-17 16:33:42 +08:00
----
2023-06-19 10:30:41 +08:00
======
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
`OAuth2AuthorizedClientProviderBuilder.builder().password()` configures a `PasswordOAuth2AuthorizedClientProvider`,
which is an implementation of an `OAuth2AuthorizedClientProvider` for the Resource Owner Password Credentials grant.
2021-12-14 06:57:36 +08:00
====
2021-05-15 10:04:28 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-password-authorized-client-manager]]
2021-11-05 01:31:27 +08:00
=== Using the Access Token
2021-05-15 10:04:28 +08:00
2024-03-27 04:22:24 +08:00
Consider the following Spring Boot properties for an OAuth 2.0 Client registration:
2021-05-15 10:04:28 +08:00
[source,yaml]
----
spring:
security:
oauth2:
client:
registration:
okta:
client-id: okta-client-id
client-secret: okta-client-secret
2021-11-05 01:31:27 +08:00
authorization-grant-type: password
scope: read, write
provider:
okta:
token-uri: https://dev-1234.oktapreview.com/oauth2/v1/token
2021-05-15 10:04:28 +08:00
----
2021-04-22 05:01:26 +08:00
Further consider the `OAuth2AuthorizedClientManager` `@Bean`:
2021-05-15 10:04:28 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-05-15 10:04:28 +08:00
[source,java,role="primary"]
----
2021-11-05 01:31:27 +08:00
@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;
}
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
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<>();
2021-05-15 10:04:28 +08:00
2021-11-05 01:31:27 +08:00
// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
};
}
2021-05-15 10:04:28 +08:00
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-05-17 16:33:42 +08:00
[source,kotlin,role="secondary"]
----
2021-11-05 01:31:27 +08:00
@Bean
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.password()
.refreshToken()
2021-05-17 16:33:42 +08:00
.build()
2021-11-05 01:31:27 +08:00
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
2021-05-17 16:33:42 +08:00
}
2021-11-05 01:31:27 +08:00
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()
2021-05-17 16:33:42 +08:00
2021-11-05 01:31:27 +08:00
// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
contextAttributes[OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME] = username
contextAttributes[OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME] = password
}
contextAttributes
}
}
2021-05-17 16:33:42 +08:00
----
2023-06-19 10:30:41 +08:00
======
2021-05-14 22:17:20 +08:00
2021-04-22 05:01:26 +08:00
Given the preceding properties and bean, you can obtain the `OAuth2AccessToken` as follows:
2019-09-12 09:15:34 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2019-09-12 09:15:34 +08:00
----
@Controller
2019-09-14 07:22:19 +08:00
public class OAuth2ClientController {
2019-09-12 09:15:34 +08:00
2021-11-05 01:31:27 +08:00
@Autowired
private OAuth2AuthorizedClientManager authorizedClientManager;
2019-09-21 03:59:11 +08:00
@GetMapping("/")
2021-11-05 01:31:27 +08:00
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);
2019-09-12 09:15:34 +08:00
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
2024-10-17 23:50:59 +08:00
// ...
2019-09-12 09:15:34 +08:00
2019-09-14 07:22:19 +08:00
return "index";
2019-09-12 09:15:34 +08:00
}
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
@Controller
class OAuth2ClientController {
2021-11-05 01:31:27 +08:00
@Autowired
private lateinit var authorizedClientManager: OAuth2AuthorizedClientManager
2020-08-11 20:07:35 +08:00
@GetMapping("/")
2021-11-05 01:31:27 +08:00
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
2020-08-11 20:07:35 +08:00
2024-10-17 23:50:59 +08:00
// ...
2020-08-11 20:07:35 +08:00
return "index"
}
}
----
2023-06-19 10:30:41 +08:00
======
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
`HttpServletRequest` and `HttpServletResponse` are both OPTIONAL attributes.
2021-04-22 05:01:26 +08:00
If not provided, they default to `ServletRequestAttributes` using `RequestContextHolder.getRequestAttributes()`.
2021-12-14 06:57:36 +08:00
====
2019-09-20 08:06:37 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-jwt-bearer]]
== [[oauth2Client-jwt-bearer-grant]]JWT Bearer
2019-09-20 08:06:37 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
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.
2021-12-14 06:57:36 +08:00
====
2019-09-20 08:06:37 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-jwt-bearer-access-token]]
2021-11-05 01:31:27 +08:00
=== Requesting an Access Token
2019-09-20 08:06:37 +08:00
2021-11-05 01:31:27 +08:00
[NOTE]
2021-12-14 06:57:36 +08:00
====
2021-11-05 01:31:27 +08:00
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.
2021-12-14 06:57:36 +08:00
====
2019-09-20 08:06:37 +08:00
2024-10-17 23:50:59 +08:00
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:
2020-08-11 20:07:35 +08:00
2024-10-17 23:50:59 +08:00
* `DefaultJwtBearerTokenResponseClient` (_default_)
* `RestClientJwtBearerTokenResponseClient`
2019-09-20 08:06:37 +08:00
2024-10-17 23:50:59 +08:00
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.
2019-09-20 08:06:37 +08:00
2024-10-17 23:50:59 +08:00
[NOTE]
2021-06-05 03:12:59 +08:00
====
2024-10-17 23:50:59 +08:00
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.
2021-06-05 03:12:59 +08:00
====
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
: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
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-jwt-bearer-authorized-client-provider-builder]]
=== Customize using the Builder
2021-11-05 01:31:27 +08:00
2024-10-17 23:50:59 +08:00
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:
2021-11-04 04:38:59 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2021-11-04 04:38:59 +08:00
[source,java,role="primary"]
----
2021-11-05 01:31:27 +08:00
// Customize
OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient = ...
JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient);
2021-11-04 04:38:59 +08:00
2021-11-05 01:31:27 +08:00
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
.build();
2021-11-04 04:38:59 +08:00
2024-10-17 23:50:59 +08:00
// ...
2021-11-04 04:38:59 +08:00
2021-11-05 01:31:27 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
2021-11-04 04:38:59 +08:00
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2021-11-04 04:38:59 +08:00
[source,kotlin,role="secondary"]
----
2021-11-05 01:31:27 +08:00
// Customize
val jwtBearerTokenResponseClient: OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> = ...
val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
2024-10-17 23:50:59 +08:00
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(jwtBearerTokenResponseClient)
2021-11-04 04:38:59 +08:00
2021-11-05 01:31:27 +08:00
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
.build()
2021-11-04 04:38:59 +08:00
2024-10-17 23:50:59 +08:00
// ...
2021-11-04 04:38:59 +08:00
2021-11-05 01:31:27 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
2021-11-04 04:38:59 +08:00
----
2023-06-19 10:30:41 +08:00
======
2021-11-04 04:38:59 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-jwt-bearer-authorized-client-manager]]
2021-11-05 01:31:27 +08:00
=== Using the Access Token
2021-11-04 04:38:59 +08:00
2024-03-27 04:22:24 +08:00
Given the following Spring Boot properties for an OAuth 2.0 Client registration:
2019-09-20 08:06:37 +08:00
2021-11-05 01:31:27 +08:00
[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
----
2019-09-20 08:06:37 +08:00
2021-11-05 01:31:27 +08:00
...and the `OAuth2AuthorizedClientManager` `@Bean`:
2019-09-20 08:06:37 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2019-09-20 08:06:37 +08:00
----
@Bean
2021-11-05 01:31:27 +08:00
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;
2019-09-20 08:06:37 +08:00
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
@Bean
2021-11-05 01:31:27 +08:00
fun authorizedClientManager(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository): OAuth2AuthorizedClientManager {
val jwtBearerAuthorizedClientProvider = JwtBearerOAuth2AuthorizedClientProvider()
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.provider(jwtBearerAuthorizedClientProvider)
2020-08-11 20:07:35 +08:00
.build()
2021-11-05 01:31:27 +08:00
val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository)
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
return authorizedClientManager
2020-08-11 20:07:35 +08:00
}
----
2023-06-19 10:30:41 +08:00
======
2020-08-11 20:07:35 +08:00
2021-11-05 01:31:27 +08:00
You may obtain the `OAuth2AccessToken` as follows:
2019-09-20 08:06:37 +08:00
2023-06-19 10:30:41 +08:00
[tabs]
======
Java::
+
2020-08-11 20:07:35 +08:00
[source,java,role="primary"]
2019-09-20 08:06:37 +08:00
----
2021-11-05 01:31:27 +08:00
@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();
2024-10-17 23:50:59 +08:00
// ...
2021-11-05 01:31:27 +08:00
}
2019-09-20 08:06:37 +08:00
}
----
2023-06-19 10:30:41 +08:00
Kotlin::
+
2020-08-11 20:07:35 +08:00
[source,kotlin,role="secondary"]
----
2021-11-05 01:31:27 +08:00
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
2024-10-17 23:50:59 +08:00
// ...
2021-11-05 01:31:27 +08:00
}
2020-08-11 20:07:35 +08:00
}
----
2023-06-19 10:30:41 +08:00
======
2022-01-08 02:23:02 +08:00
[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>`.
2024-03-26 06:01:09 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-token-exchange]]
== [[oauth2Client-token-exchange-grant]]Token Exchange
2024-03-26 06:01:09 +08:00
[NOTE]
====
Please refer to OAuth 2.0 Token Exchange for further details on the https://datatracker.ietf.org/doc/html/rfc8693[Token Exchange] grant.
====
2024-10-17 23:50:59 +08:00
[[oauth2-client-token-exchange-access-token]]
2024-03-26 06:01:09 +08:00
=== 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.
====
2024-10-17 23:50:59 +08:00
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:
2024-03-26 06:01:09 +08:00
2024-10-17 23:50:59 +08:00
* `DefaultTokenExchangeTokenResponseClient` (_default_)
* `RestClientTokenExchangeTokenResponseClient`
2024-03-26 06:01:09 +08:00
2024-10-17 23:50:59 +08:00
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.
2024-03-26 06:01:09 +08:00
2024-10-17 23:50:59 +08:00
[NOTE]
2024-03-26 06:01:09 +08:00
====
2024-10-17 23:50:59 +08:00
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.
2024-03-26 06:01:09 +08:00
====
2024-10-17 23:50:59 +08:00
: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
2024-03-26 06:01:09 +08:00
2024-10-17 23:50:59 +08:00
[[oauth2-client-token-exchange-authorized-client-provider-builder]]
=== Customize using the Builder
2024-03-26 06:01:09 +08:00
2024-10-17 23:50:59 +08:00
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:
2024-03-26 06:01:09 +08:00
[tabs]
======
Java::
+
[source,java,role="primary"]
----
// Customize
OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> tokenExchangeTokenResponseClient = ...
TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider = new TokenExchangeOAuth2AuthorizedClientProvider();
tokenExchangeAuthorizedClientProvider.setAccessTokenResponseClient(tokenExchangeTokenResponseClient);
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.provider(tokenExchangeAuthorizedClientProvider)
.build();
2024-10-17 23:50:59 +08:00
// ...
2024-03-26 06:01:09 +08:00
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()
2024-10-17 23:50:59 +08:00
// ...
2024-03-26 06:01:09 +08:00
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)
----
======
2024-10-17 23:50:59 +08:00
[[oauth2-client-token-exchange-authorized-client-manager]]
=== [[token-exchange-grant-access-token]]Using the Access Token
2024-03-26 06:01:09 +08:00
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();
2024-10-17 23:50:59 +08:00
// ...
2024-03-26 06:01:09 +08:00
}
}
----
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
2024-10-17 23:50:59 +08:00
// ...
2024-03-26 06:01:09 +08:00
}
}
----
======
[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>`.