OAuth2 Client and Authorization Code Flow
Configure the OAuth2 client to obtain and refresh tokens via the authorization code grant.
Why an OAuth2 Client?
When your Spring Boot app needs to act on behalf of a user against an external provider (Google, GitHub, Keycloak, Okta), it becomes an OAuth2 Client.
The client never sees the user's password. Instead it redirects the browser to the provider's authorization endpoint, the user logs in there, and the provider hands back an access_token (and optionally a refresh_token) that the client uses to call protected APIs.
- Authorization Code grant is the recommended browser-based flow.
- Spring Security's
spring-boot-starter-oauth2-clientimplements the entire dance for you.
Adding the Starter
Bring in the OAuth2 client support. In Spring Boot 4 this lives in spring-boot-starter-oauth2-client, which transitively pulls in spring-security-oauth2-client and the JOSE/JWT libraries needed for OIDC.
This Maven dependency is all you need to enable login-with-provider and token acquisition.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>All lessons in this course
- Resource Server JWT Validation and Claims
- OAuth2 Client and Authorization Code Flow
- Method Security with SpEL and Custom Voters
- Opaque Token Introspection and Token Exchange