Spring Security's OAuth 2.0 support consists of two primary feature sets:
* <<oauth2-resource-server>>
* <<oauth2-client>>
[NOTE]
====
<<oauth2-client-log-users-in,OAuth2 Login>> is a very powerful OAuth2 Client feature that deserves its own section in the reference documentation.
However, it does not exist as a standalone feature and requires OAuth2 Client in order to function.
====
These feature sets cover the _resource server_ and _client_ roles defined in the https://tools.ietf.org/html/rfc6749#section-1.1[OAuth 2.0 Authorization Framework], while the _authorization server_ role is covered by https://docs.spring.io/spring-authorization-server/reference/index.html[Spring Authorization Server], which is a separate project built on xref:index.adoc[Spring Security].
The _resource server_ and _client_ roles in OAuth2 are typically represented by one or more server-side applications.
Additionally, the _authorization server_ role can be represented by one or more third parties (as is the case when centralizing identity management and/or authentication within an organization) *-or-* it can be represented by an application (as is the case with Spring Authorization Server).
For example, a typical OAuth2-based microservices architecture might consist of a single user-facing client application, several backend resource servers providing REST APIs and a third party authorization server for managing users and authentication concerns.
It is also common to have a single application representing only one of these roles with the need to integrate with one or more third parties that are providing the other roles.
Spring Security handles these scenarios and more.
The following sections cover the roles provided by Spring Security and contain examples for common scenarios.
[[oauth2-resource-server]]
== OAuth2 Resource Server
[NOTE]
====
This section contains a summary of OAuth2 Resource Server features with examples.
See xref:reactive/oauth2/resource-server/index.adoc[OAuth 2.0 Resource Server] for complete reference documentation.
====
To get started, add the `spring-security-oauth2-resource-server` dependency to your project.
When using Spring Boot, add the following starter:
Spring Security does not provide an endpoint for minting tokens.
However, Spring Security does provide the `JwtEncoder` interface along with one implementation, which is `NimbusJwtEncoder`.
====
[[oauth2-client]]
== OAuth2 Client
[NOTE]
====
This section contains a summary of OAuth2 Client features with examples.
See xref:reactive/oauth2/client/index.adoc[OAuth 2.0 Client] and xref:reactive/oauth2/login/index.adoc[OAuth 2.0 Login] for complete reference documentation.
====
To get started, add the `spring-security-oauth2-client` dependency to your project.
When using Spring Boot, add the following starter:
It is very common to require users to log in via OAuth2.
https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect 1.0] provides a special token called the `id_token` which is designed to provide an OAuth2 Client with the ability to perform user identity verification and log users in.
In certain cases, OAuth2 can be used directly to log users in (as is the case with popular social login providers that do not implement OpenID Connect such as GitHub and Facebook).
The following example configures the application to act as an OAuth2 Client capable of logging users in with OAuth2 or OpenID Connect:
.Configure OAuth2 Login
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
// ...
oauth2Login { }
}
}
}
----
=====
In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ReactiveClientRegistrationRepository` bean.
The following example configures an `InMemoryReactiveClientRegistrationRepository` bean using Spring Boot configuration properties:
[source,yaml]
----
spring:
security:
oauth2:
client:
registration:
my-oidc-client:
provider: my-oidc-provider
client-id: my-client-id
client-secret: my-client-secret
authorization-grant-type: authorization_code
scope: openid,profile
provider:
my-oidc-provider:
issuer-uri: https://my-oidc-provider.com
----
With the above configuration, the application now supports two additional endpoints:
1. The login endpoint (e.g. `/oauth2/authorization/my-oidc-client`) is used to initiate login and perform a redirect to the third party authorization server.
2. The redirection endpoint (e.g. `/login/oauth2/code/my-oidc-client`) is used by the authorization server to redirect back to the client application, and will contain a `code` parameter used to obtain an `id_token` and/or `access_token` via the access token request.
[NOTE]
====
The presence of the `openid` scope in the above configuration indicates that OpenID Connect 1.0 should be used.
This instructs Spring Security to use OIDC-specific components (such as `OidcReactiveOAuth2UserService`) during request processing.
Without this scope, Spring Security will use OAuth2-specific components (such as `DefaultReactiveOAuth2UserService`) instead.
====
[[oauth2-client-access-protected-resources]]
=== Access Protected Resources
Making requests to a third party API that is protected by OAuth2 is a core use case of OAuth2 Client.
This is accomplished by authorizing a client (represented by the `OAuth2AuthorizedClient` class in Spring Security) and accessing protected resources by placing a `Bearer` token in the `Authorization` header of an outbound request.
The following example configures the application to act as an OAuth2 Client capable of requesting protected resources from a third party API:
.Configure OAuth2 Client
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
// ...
oauth2Client { }
}
}
}
----
=====
[NOTE]
====
The above example does not provide a way to log users in.
You can use any other login mechanism (such as `formLogin()`).
See the <<oauth2-client-access-protected-resources-current-user,next section>> for an example combining `oauth2Client()` with `oauth2Login()`.
====
In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ReactiveClientRegistrationRepository` bean.
The following example configures an `InMemoryReactiveClientRegistrationRepository` bean using Spring Boot configuration properties:
[source,yaml]
----
spring:
security:
oauth2:
client:
registration:
my-oauth2-client:
provider: my-auth-server
client-id: my-client-id
client-secret: my-client-secret
authorization-grant-type: authorization_code
scope: message.read,message.write
provider:
my-auth-server:
issuer-uri: https://my-auth-server.com
----
In addition to configuring Spring Security to support OAuth2 Client features, you will also need to decide how you will be accessing protected resources and configure your application accordingly.
Spring Security provides implementations of `ReactiveOAuth2AuthorizedClientManager` for obtaining access tokens that can be used to access protected resources.
[TIP]
====
Spring Security registers a default `ReactiveOAuth2AuthorizedClientManager` bean for you when one does not exist.
====
The easiest way to use a `ReactiveOAuth2AuthorizedClientManager` is via an `ExchangeFilterFunction` that intercepts requests through a `WebClient`.
The following example uses the default `ReactiveOAuth2AuthorizedClientManager` to configure a `WebClient` capable of accessing protected resources by placing `Bearer` tokens in the `Authorization` header of each request:
.Configure `WebClient` with `ExchangeFilterFunction`
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
=== Access Protected Resources for the Current User
When a user is logged in via OAuth2 or OpenID Connect, the authorization server may provide an access token that can be used directly to access protected resources.
This is convenient because it only requires a single `ClientRegistration` to be configured for both use cases simultaneously.
[NOTE]
====
This section combines <<oauth2-client-log-users-in>> and <<oauth2-client-access-protected-resources>> into a single configuration.
Other advanced scenarios exist, such as configuring one `ClientRegistration` for login and another for accessing protected resources.
All such scenarios would use the same basic configuration.
====
The following example configures the application to act as an OAuth2 Client capable of logging the user in _and_ requesting protected resources from a third party API:
.Configure OAuth2 Login and OAuth2 Client
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
// ...
oauth2Login { }
oauth2Client { }
}
}
}
----
=====
In addition to the above configuration, the application requires at least one `ClientRegistration` to be configured through the use of a `ReactiveClientRegistrationRepository` bean.
The following example configures an `InMemoryReactiveClientRegistrationRepository` bean using Spring Boot configuration properties:
[source,yaml]
----
spring:
security:
oauth2:
client:
registration:
my-combined-client:
provider: my-auth-server
client-id: my-client-id
client-secret: my-client-secret
authorization-grant-type: authorization_code
scope: openid,profile,message.read,message.write
provider:
my-auth-server:
issuer-uri: https://my-auth-server.com
----
[NOTE]
====
The main difference between the previous examples (<<oauth2-client-log-users-in>>, <<oauth2-client-access-protected-resources>>) and this one is what is configured via the `scope` property, which combines the standard scopes `openid` and `profile` with the custom scopes `message.read` and `message.write`.
====
In addition to configuring Spring Security to support OAuth2 Client features, you will also need to decide how you will be accessing protected resources and configure your application accordingly.
Spring Security provides implementations of `ReactiveOAuth2AuthorizedClientManager` for obtaining access tokens that can be used to access protected resources.
[TIP]
====
Spring Security registers a default `ReactiveOAuth2AuthorizedClientManager` bean for you when one does not exist.
====
The easiest way to use a `ReactiveOAuth2AuthorizedClientManager` is via an `ExchangeFilterFunction` that intercepts requests through a `WebClient`.
The following example uses the default `ReactiveOAuth2AuthorizedClientManager` to configure a `WebClient` capable of accessing protected resources by placing `Bearer` tokens in the `Authorization` header of each request:
.Configure `WebClient` with `ExchangeFilterFunction`
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
.Use `WebClient` to Access Protected Resources (Current User)
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@RestController
public class MessagesController {
private final WebClient webClient;
public MessagesController(WebClient webClient) {
this.webClient = webClient;
}
@GetMapping("/messages")
public Mono<ResponseEntity<List<Message>>> messages() {
return this.webClient.get()
.uri("http://localhost:8090/messages")
.retrieve()
.toEntityList(Message.class);
}
public record Message(String message) {
}
}
----
Kotlin::
+
[source,kotlin,role="secondary"]
----
@RestController
class MessagesController(private val webClient: WebClient) {
@GetMapping("/messages")
fun messages(): Mono<ResponseEntity<List<Message>>> {
return webClient.get()
.uri("http://localhost:8090/messages")
.retrieve()
.toEntityList<Message>()
}
data class Message(val message: String)
}
----
=====
[NOTE]
====
Unlike the <<oauth2-client-accessing-protected-resources-example,previous example>>, notice that we do not need to tell Spring Security about the `clientRegistrationId` we'd like to use.
This is because it can be derived from the currently logged in user.
====
[[oauth2-client-enable-extension-grant-type]]
=== Enable an Extension Grant Type
A common use case involves enabling and/or configuring an extension grant type.
For example, Spring Security provides support for the `jwt-bearer` and `token-exchange` grant types, but does not enable them by default because they are not part of the core OAuth 2.0 specification.
With Spring Security 6.3 and later, we can simply publish a bean for one or more `ReactiveOAuth2AuthorizedClientProvider` and they will be picked up automatically.
The following example simply enables the `jwt-bearer` grant type:
.Enable `jwt-bearer` Grant Type
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class SecurityConfig {
@Bean
public ReactiveOAuth2AuthorizedClientProvider jwtBearer() {
return new JwtBearerReactiveOAuth2AuthorizedClientProvider();
}
}
----
Kotlin::
+
[source,kotlin,role="secondary"]
----
@Configuration
class SecurityConfig {
@Bean
fun jwtBearer(): ReactiveOAuth2AuthorizedClientProvider {
A default `ReactiveOAuth2AuthorizedClientManager` will be published automatically by Spring Security when one is not already provided.
[TIP]
====
Any custom `OAuth2AuthorizedClientProvider` bean will also be picked up and applied to the provided `ReactiveOAuth2AuthorizedClientManager` after the default grant types.
====
In order to achieve the above configuration prior to Spring Security 6.3, we had to publish this bean ourselves and ensure we re-enabled default grant types as well.
To understand what is being configured behind the scenes, here's what the configuration might have looked like:
.Enable `jwt-bearer` Grant Type (prior to 6.3)
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class SecurityConfig {
@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
The ability to <<oauth2-client-enable-extension-grant-type,enable extension grant types>> by publishing a bean also provides the opportunity for customizing an existing grant type without the need to re-define the defaults.
For example, if we want to customize the clock skew of the `ReactiveOAuth2AuthorizedClientProvider` for the `client_credentials` grant, we can simply publish a bean like so:
.Customize Client Credentials Grant Type
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class SecurityConfig {
@Bean
public ReactiveOAuth2AuthorizedClientProvider clientCredentials() {
The need to customize request parameters when obtaining an access token is fairly common.
For example, let's say we want to add a custom `audience` parameter to the token request because the provider requires this parameter for the `authorization_code` grant.
We can simply publish a bean of type `ReactiveOAuth2AccessTokenResponseClient` with the generic type `OAuth2AuthorizationCodeGrantRequest` and it will be used by Spring Security to configure OAuth2 Client components.
The following example customizes token request parameters for the `authorization_code` grant:
.Customize Token Request Parameters for Authorization Code Grant
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class SecurityConfig {
@Bean
public ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> authorizationCodeAccessTokenResponseClient() {
Notice that we don't need to customize the `SecurityWebFilterChain` bean in this case, and can stick with the defaults.
If using Spring Boot with no additional customizations, we can actually omit the `SecurityWebFilterChain` bean entirely.
====
As you can see, providing the `ReactiveOAuth2AccessTokenResponseClient` as a bean is quite convenient.
When using the Spring Security DSL directly, we need to ensure that this customization is applied for both OAuth2 Login (if we are using this feature) and OAuth2 Client components.
To understand what is being configured behind the scenes, here's what the configuration would look like with the DSL:
.Customize Token Request Parameters for Authorization Code Grant using the DSL
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
private fun parametersConverter(): Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> {
// ...
}
}
----
=====
Spring Security automatically resolves the following generic types of `ReactiveOAuth2AccessTokenResponseClient` beans:
* `OAuth2AuthorizationCodeGrantRequest` (see `WebClientReactiveAuthorizationCodeTokenResponseClient`)
* `OAuth2RefreshTokenGrantRequest` (see `WebClientReactiveRefreshTokenTokenResponseClient`)
* `OAuth2ClientCredentialsGrantRequest` (see `WebClientReactiveClientCredentialsTokenResponseClient`)
* `OAuth2PasswordGrantRequest` (see `WebClientReactivePasswordTokenResponseClient`)
* `JwtBearerGrantRequest` (see `WebClientReactiveJwtBearerTokenResponseClient`)
* `TokenExchangeGrantRequest` (see `WebClientReactiveTokenExchangeTokenResponseClient`)
[TIP]
====
Publishing a bean of type `ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest>` will automatically enable the `jwt-bearer` grant type without the need to <<oauth2-client-enable-extension-grant-type,configure it separately>>.
====
[TIP]
====
Publishing a bean of type `ReactiveOAuth2AccessTokenResponseClient<TokenExchangeGrantRequest>` will automatically enable the `token-exchange` grant type without the need to <<oauth2-client-enable-extension-grant-type,configure it separately>>.
====
[[oauth2-client-customize-web-client]]
=== Customize the `WebClient` used by OAuth2 Client Components
Another common use case is the need to customize the `WebClient` used when obtaining an access token.
We might need to do this to customize the underlying HTTP client library (via a custom `ClientHttpConnector`) to configure SSL settings or to apply proxy settings for a corporate network.
With Spring Security 6.3 and later, we can simply publish beans of type `ReactiveOAuth2AccessTokenResponseClient` and Spring Security will configure and publish a `ReactiveOAuth2AuthorizedClientManager` bean for us.
The following example customizes the `WebClient` for all of the supported grant types:
.Customize `WebClient` for OAuth2 Client
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class SecurityConfig {
@Bean
public ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> authorizationCodeAccessTokenResponseClient() {
A default `ReactiveOAuth2AuthorizedClientManager` will be published automatically by Spring Security when one is not already provided.
[TIP]
====
Notice that we don't need to customize the `SecurityWebFilterChain` bean in this case, and can stick with the defaults.
If using Spring Boot with no additional customizations, we can actually omit the `SecurityWebFilterChain` bean entirely.
====
Prior to Spring Security 6.3, we had to ensure this customization was applied to OAuth2 Client components ourselves.
While we could publish a bean of type `ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest>` for the `authorization_code` grant, we had to publish a bean of type `ReactiveOAuth2AuthorizedClientManager` for other grant types.
To understand what is being configured behind the scenes, here's what the configuration might have looked like:
.Customize `WebClient` for OAuth2 Client (prior to 6.3)
[tabs]
=====
Java::
+
[source,java,role="primary"]
----
@Configuration
public class SecurityConfig {
@Bean
public ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> authorizationCodeAccessTokenResponseClient() {