OAuth2 & OIDC in Spring Boot
Spring Security OAuth2 client, Resource Server configuration, OIDC login, JWT decoder
- Configure Spring Boot as an OAuth2 Resource Server with JWT
- Implement OIDC login with Google/GitHub via spring-security-oauth2-client
- Map ID token claims to Spring Security authorities
A comprehensive reference covering OAuth2 concepts, OIDC differences, Spring Boot implementation, stateful vs stateless flows, and internal Spring Security filter mechanics.
Table of Contents
- What is OAuth 2.0?
- OAuth 2.0 Grant Types
- Authorization Code Grant Flow — Deep Dive
- OAuth 2.0 vs OpenID Connect (OIDC)
- Tokens: Opaque vs JWT vs ID Token
- Spring Boot OAuth2 Implementation — Step by Step
- How Spring Security Handles OAuth2 Internally
- Stateful vs Stateless OAuth2 in Spring Boot
- Making OAuth2 Stateless — Custom Success Handler & Validation Filter
- Complete Internal Flow Diagram
- Key Observations & Best Practices
- Common Mistakes
- Interview Notes
- Summary — Revision Bullets
1. What is OAuth 2.0?
Overview
OAuth 2.0 stands for Open Authorization Framework. It is an industry-standard protocol that enables a third-party application to obtain limited, secure access to a user's protected data on another service — without the user ever sharing their password with that third-party app.
Why This Concept Exists
Before OAuth, if you wanted a third-party app (say, Instagram) to access your Gmail contacts, you would have to give Instagram your Gmail username and password directly. This is dangerous because:
- The third-party stores your credentials.
- It has full access to your account, not just what you intended to share.
- You cannot revoke access without changing your password.
OAuth 2.0 solves this by introducing a token-based delegation model.
Real-World Analogy
Think of OAuth like a hotel key card. When you check in, the hotel (Authorization Server) gives you a key card (access token) that only opens your room (specific resource). You don't get a master key. The hotel can deactivate the key at any time, and you never needed to give anyone else your home key.
Core Participants
| Role | Description | Example |
|---|---|---|
| Resource Owner | The actual user who owns the data | You / Me |
| Resource Server | The server hosting protected data | Gmail API, GitHub API |
| Authorization Server | Issues tokens after authenticating the user | Gmail Auth Server, Auth0, GitLab |
| Client (Third-Party App) | Application requesting access on behalf of the user | Instagram, your Spring Boot app |
2. OAuth 2.0 Grant Types
OAuth 2.0 defines multiple "grant types" — different flows for obtaining tokens depending on the use case:
| Grant Type | Use Case |
|---|---|
| Authorization Code Grant | Web/mobile apps with a backend server (most secure, most common) |
| Implicit Grant | Single-page apps (deprecated; less secure) |
| Client Credentials | Machine-to-machine (no user involved) |
| Resource Owner Password Credentials | Highly trusted apps (user provides credentials directly to client) |
| Refresh Token | Obtaining new access tokens without re-authentication |
3. Authorization Code Grant Flow Deep Dive
Overview
In the Authorization Code Grant flow, the client never sees the user's credentials. Instead, it receives a short-lived authorization code which it then exchanges for an access token.
Step-by-Step Flow
◆ Step 1 Client Registration
Before the flow begins, the third-party app must register itself with the Authorization Server (e.g., GitLab, Auth0, Google).
During registration, you provide:
- Application Name
- Redirect URI — the URL the Authorization Server will call back with the authorization code
- Scopes — what data/permissions you need (e.g.,
openid,read,write)
In return, the Authorization Server gives you:
- Client ID — a public identifier for your app
- Client Secret — a private secret known only to your app and the Authorization Server
◆ Step 2 User Initiates Login
The user visits the third-party app (your Spring Boot app) and clicks "Sign in with Gmail" (or GitLab, Auth0, etc.).
◆ Step 3 Redirect to Authorization Server
The third-party app redirects the user's browser to the Authorization Server's authorization endpoint, including:
client_idredirect_uriscoperesponse_type=codestate(CSRF protection token)
◆ Step 4 User Authenticates & Grants Consent
The Authorization Server (e.g., GitLab) shows the user a login page. The user:
- Enters their credentials (username/password for GitLab/Auth0).
- Reviews what data the third-party app is requesting.
- Grants consent.
◆ Step 5 Authorization Code Returned
After successful authentication and consent, the Authorization Server calls the redirect URI with an authorization code appended as a query parameter:
1https://your-spring-app.com/login/oauth2/code/gitlab?code=AUTH_CODE_HERE&state=STATE_VALUE◆ Step 6 Exchange Code for Token
The third-party app (Spring Boot backend) sends a POST request to the Authorization Server's token endpoint, including:
code— the authorization code receivedclient_idclient_secretredirect_urigrant_type=authorization_code
◆ Step 7 Token Response
The Authorization Server validates everything and responds with:
- Access Token — used to call protected APIs
- Refresh Token — used to get new access tokens
- ID Token (if using OIDC scope) — contains user identity information
◆ Step 8 Access Protected Resources
The third-party app uses the access token to call the Resource Server's APIs (e.g., Gmail API) to fetch user data.
Authorization Code Flow Diagram
4. OAuth 2.0 vs OpenID Connect (OIDC)
This is one of the most commonly confused distinctions in the auth space.
Comparison Table
| Feature | OAuth 2.0 | OpenID Connect (OIDC) |
|---|---|---|
| Full Name | Open Authorization | OpenID Connect |
| Purpose | Authorization — granting access to resources | Authentication — verifying user identity |
| Built On | Base protocol | Built on top of OAuth 2.0 |
| Token Received | Access Token (opaque or JWT) | ID Token (JWT) + Access Token |
| Token Used For | Calling resource server APIs to fetch data | Authenticating the user within the client app |
| Token Sent to Resource Server? | Yes | ID Token: NO. Access Token: Yes (if needed) |
| Scope | read, write, etc. | openid (mandatory), plus optional profile, email |
| User Info in Token? | Not necessarily | Yes — ID Token contains user identity claims |
The Key Difference Explained
OAuth 2.0 (Authorization):
- The access token can be used to call APIs on the resource server.
- Example: Instagram gets an access token and calls
GET /gmail/emailsto read your emails. - The token can be opaque (only the auth server understands it) or JWT.
OIDC (Authentication):
- The ID token is a JWT containing minimal user information (e.g.,
sub,name,email,picture). - This ID token is only for the client app — it tells the app "this user is who they say they are."
- The ID token is never sent to the resource server.
- Since OIDC is built on top of OAuth 2.0, you also get an access token if you need to call APIs.
Visual Distinction
scope=openid during app registration (as done in GitLab/Auth0 in this lecture), you are telling the Authorization Server: "I only need to authenticate the user, not access their protected data."5. Tokens: Opaque vs JWT vs ID Token
Opaque Token
- A random string with no human-readable content.
- Only the Authorization Server can understand/validate it (by looking it up in its database).
- Example: What GitLab returns as an access token.
- The third-party app cannot decode it directly.
1access_token: "sl.BDd9jkX3nM5Qf7YzVx2pW..."JWT Token (JSON Web Token)
- Has three parts separated by dots:
header.payload.signature - The client can decode the payload (base64) to read claims.
- Verified using the Authorization Server's public key.
- Used for stateless token validation.
1eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIiwibmFtZSI6IkpvaG4ifQ.SIGNATUREID Token (OIDC-specific)
- Always a JWT (never opaque).
- Contains minimal claims about the authenticated user:
sub— unique user identifiername,email,pictureiss— issuer (who created the token)aud— audience (who this token is for)exp— expiration time- Meant for the client app only, not for resource servers.
- Used to authenticate the user without any additional API calls.
Token Comparison Table
| Feature | Opaque Token | JWT Access Token | ID Token |
|---|---|---|---|
| Format | Random string | header.payload.signature | JWT (always) |
| Decodable | No (only auth server) | Yes (base64) | Yes (base64) |
| Purpose | Access resources | Access resources | Authenticate user |
| Sent to Resource Server? | Yes | Yes | No |
| Signature Algorithm | N/A | HS256 / RS256 | RS256 (typical for OIDC) |
6. Spring Boot OAuth2 Implementation Step by Step
Prerequisites
This implementation assumes:
- Java 17+ and Spring Boot 3.x
- Maven project
- An account on GitLab and/or Auth0 for client registration
Step 1 Register Your App with the Authorization Server
◆ GitLab Registration
- Go to your GitLab profile → Settings → Applications
- Click Add new application
- Fill in:
- Name:
MySpringBootApp(or any name) - Redirect URI:
http://localhost:8080/login/oauth2/code/gitlab - Scopes: Select
openid(for authentication only)
- Click Save application
- Copy the Application ID (Client ID) and Secret
◆ Auth0 Registration
- Log in to auth0.com → Applications → Create Application
- Choose Regular Web Applications
- Set Allowed Callback URLs:
http://localhost:8080/login/oauth2/code/auth0 - Under settings, configure:
- OIDC Conformant: ON
- Token Endpoint Auth Method: Post
- JWT Signing Algorithm: RS256
- Copy Client ID and Client Secret
Step 2 Add Maven Dependency
1<!-- pom.xml -->2<dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-oauth2-client</artifactId>5</dependency>Step 3 Configure `application.properties`
1# ===================== GitLab Configuration =====================2spring.security.oauth2.client.registration.gitlab.client-id=YOUR_GITLAB_CLIENT_ID3spring.security.oauth2.client.registration.gitlab.client-secret=YOUR_GITLAB_CLIENT_SECRET4spring.security.oauth2.client.registration.gitlab.scope=openid5spring.security.oauth2.client.registration.gitlab.authorization-grant-type=authorization_code6spring.security.oauth2.client.registration.gitlab.redirect-uri=http://localhost:8080/login/oauth2/code/gitlab7
8spring.security.oauth2.client.provider.gitlab.authorization-uri=https://gitlab.com/oauth/authorize9spring.security.oauth2.client.provider.gitlab.token-uri=https://gitlab.com/oauth/token10spring.security.oauth2.client.provider.gitlab.user-info-uri=https://gitlab.com/oauth/userinfo11spring.security.oauth2.client.provider.gitlab.jwk-set-uri=https://gitlab.com/oauth/discovery/keys12spring.security.oauth2.client.provider.gitlab.issuer-uri=https://gitlab.com13
14# ===================== Auth0 Configuration =====================15spring.security.oauth2.client.registration.auth0.client-id=YOUR_AUTH0_CLIENT_ID16spring.security.oauth2.client.registration.auth0.client-secret=YOUR_AUTH0_CLIENT_SECRET17spring.security.oauth2.client.registration.auth0.scope=openid18spring.security.oauth2.client.registration.auth0.authorization-grant-type=authorization_code19spring.security.oauth2.client.registration.auth0.redirect-uri=http://localhost:8080/login/oauth2/code/auth020
21spring.security.oauth2.client.provider.auth0.issuer-uri=https://YOUR_AUTH0_DOMAIN.auth0.com/◆ Configuration Properties Explained
| Property | Purpose |
|---|---|
client-id | Your app's public identifier from the auth server |
client-secret | Your app's private secret |
scope | What permissions to request (openid = authentication only) |
authorization-grant-type | Which OAuth2 flow to use |
redirect-uri | Where the auth server sends the authorization code back |
authorization-uri | The auth server endpoint to initiate login |
token-uri | Where Spring exchanges the code for a token |
user-info-uri | Endpoint to fetch user profile info |
jwk-set-uri | URL of the public key used to verify JWT signatures |
issuer-uri | Identity of the authorization server |
registration. and provider. — in this case gitlab and auth0. Spring uses these IDs to match configuration and build the login page links automatically.Step 4 Security Configuration
1// SecurityConfig.java2import org.springframework.context.annotation.Bean;3import org.springframework.context.annotation.Configuration;4import org.springframework.security.config.annotation.web.builders.HttpSecurity;5import org.springframework.security.web.SecurityFilterChain;6
7@Configuration8public class SecurityConfig {9
10 @Bean11 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {12 http13 .authorizeHttpRequests(auth -> auth14 .anyRequest().authenticated()15 )16 .oauth2Login(oauth2 -> oauth217 .withDefaults() // Use Spring's default OAuth2 login page18 );19 return http.build();20 }21}◆ Line-by-Line Explanation
anyRequest().authenticated()— every endpoint requires a logged-in user..oauth2Login(oauth2 -> oauth2.withDefaults())— enables the default OAuth2 login page at/login, which Spring auto-generates showing all configured authorization servers.
Step 5 Basic Controller
1// HomeController.java2import org.springframework.web.bind.annotation.GetMapping;3import org.springframework.web.bind.annotation.RestController;4
5@RestController6public class HomeController {7
8 @GetMapping("/")9 public String home() {10 return "Hello, you are logged in!";11 }12
13 @GetMapping("/user")14 public String user() {15 return "Fetch the details successfully!";16 }17}What Works Out of the Box
With just these three changes — pom.xml, application.properties, and SecurityConfig — Spring Boot handles the entire OAuth2 authorization code flow automatically:
- Auto-generates the login page at
/loginshowing all configured auth servers. - Handles the redirect to the authorization server.
- Handles the redirect URI callback with the authorization code.
- Exchanges the code for tokens behind the scenes.
- Creates an HTTP session for the authenticated user.
- Protects all endpoints.
7. How Spring Security Handles OAuth2 Internally
This section explains the internal filter chain that Spring Security executes during OAuth2 login — the "behind the scenes" mechanics.
Phase 1 Generating the Login Page
Filter: DefaultLoginPageGeneratingFilter
When the user hits any protected URL (e.g., localhost:8080), Spring redirects them to /login. The DefaultLoginPageGeneratingFilter generates the HTML login page.
It reads from the OAuth2 client registration configuration (loaded from application.properties) and generates a list of authorization servers the user can choose from.
Internally, it iterates over OAuth2AuthorizationRequestRedirectFilter's URL map and renders a link for each registration ID.
Phase 2 User Clicks an Authorization Server Link
Endpoint invoked: /oauth2/authorization/{registrationId}
For example, if the user clicks "GitLab":
1GET /oauth2/authorization/gitlabFilter: OAuth2AuthorizationRequestRedirectFilter
This filter intercepts the above URL pattern. It:
- Builds the full authorization URL for the selected auth server (using the
authorization-urifrom properties). - Appends
client_id,redirect_uri,scope,response_type=code, and a randomstatevalue. - Redirects the user's browser to the Authorization Server.
The flow then leaves your Spring Boot app. The user is now on GitLab's or Auth0's login page.
Phase 3 User Authenticates on the Authorization Server
This happens entirely on the external server (GitLab, Auth0). The user:
- Enters their credentials.
- Approves the consent screen.
The authorization server then calls your redirect URI:
1GET http://localhost:8080/login/oauth2/code/gitlab?code=AUTH_CODE&state=STATEPhase 4 Spring Receives the Authorization Code
Filter: OAuth2LoginAuthenticationFilter
This filter is configured to intercept the redirect URI pattern /login/oauth2/code/*.
It:
- Extracts the
codeandstatefrom the request. - Creates an
OAuth2LoginAuthenticationTokenobject containing the authorization code. - Passes this token to the
AuthenticationManager.
Phase 5 Authentication Provider Processes the Token
Authentication Manager delegates to the appropriate Authentication Provider.
Since we are using scope=openid (OIDC), the provider is:
OidcAuthorizationCodeAuthenticationProvider
This provider:
- Takes the
OAuth2LoginAuthenticationToken. - Calls the Authorization Server's token endpoint (
token-urifrom config) with:
codeclient_idclient_secretgrant_type=authorization_code
- Receives the response containing
access_token,refresh_token, andid_token. - Parses and validates the ID token (JWT).
- Returns the authentication result back to the filter.
Phase 6 Session Creation and Storage
Back in OAuth2LoginAuthenticationFilter, after successful authentication:
- Stores tokens: The access token, refresh token, and ID token are stored in an in-memory
OAuth2AuthorizedClientService.
OAuth2AuthorizedClientService to store tokens in a database instead of in-memory.- Creates HTTP session: A
SecurityContextis created containing the authentication object. This is stored viaHttpSessionSecurityContextRepository, creating a session cookie.
- Redirects the user to the originally requested URL (e.g.,
localhost:8080/).
Phase 7 Subsequent Requests
Filter: SecurityContextHolderFilter → HttpSessionSecurityContextRepository
For every subsequent request:
- The filter reads the session ID from the cookie.
- Looks up the session in memory.
- If the session is active, the request is considered authenticated — without re-validating the token.
Internal Flow Diagram
8. Stateful vs Stateless OAuth2 in Spring Boot
The Default: Stateful
By default, Spring Boot's OAuth2 login creates an HTTP session. This means:
- Session is stored server-side.
- A session cookie is sent to the browser.
- Every request checks the session — not the token.
- Works perfectly in a browser.
Problem: When a REST client like Postman tries to access the API, it does not carry the session cookie, so it gets a redirect to the login page even after authentication.
Why This is a Problem for APIs
Modern applications (especially mobile apps, SPAs, microservices) are stateless — they don't maintain sessions. They expect to:
- Login → receive a token.
- Include the token in every subsequent request.
- The server validates the token each time.
The Solution: Stateless OAuth2
To make OAuth2 stateless in Spring Boot:
- Return the ID token in the login response (via a custom success handler).
- Validate the token on every request (via a custom filter).
- Disable session creation in the security config.
9. Making OAuth2 Stateless Custom Success Handler & Validation Filter
Step 1 Custom Authentication Success Handler
1// CustomOAuth2SuccessHandler.java2import jakarta.servlet.http.HttpServletRequest;3import jakarta.servlet.http.HttpServletResponse;4import org.springframework.security.core.Authentication;5import org.springframework.security.oauth2.core.oidc.user.OidcUser;6import org.springframework.security.web.authentication.AuthenticationSuccessHandler;7import org.springframework.stereotype.Component;8
9import java.io.IOException;10
11@Component12public class CustomOAuth2SuccessHandler implements AuthenticationSuccessHandler {13
14 @Override15 public void onAuthenticationSuccess(HttpServletRequest request,16 HttpServletResponse response,17 Authentication authentication) throws IOException {18
19 // Cast the authenticated principal to OidcUser to access OIDC-specific data20 OidcUser oidcUser = (OidcUser) authentication.getPrincipal();21
22 // Extract the ID Token value (JWT string)23 String idToken = oidcUser.getIdToken().getTokenValue();24
25 // Write the ID token into the HTTP response body26 response.setContentType("application/json");27 response.getWriter().write("{\"id_token\": \"" + idToken + "\"}");28 response.getWriter().flush();29 }30}◆ Line-by-Line Explanation
AuthenticationSuccessHandler— Spring Security interface; itsonAuthenticationSuccessmethod is called after successful authentication.OidcUser— the authenticated principal when using OIDC; contains the ID token and user claims.oidcUser.getIdToken().getTokenValue()— extracts the raw JWT string of the ID token.- The ID token is written into the HTTP response so the client (browser/Postman/mobile app) can capture and store it.
Step 2 Updated Security Config (Stateless)
1// SecurityConfig.java2import org.springframework.beans.factory.annotation.Autowired;3import org.springframework.context.annotation.Bean;4import org.springframework.context.annotation.Configuration;5import org.springframework.security.config.annotation.web.builders.HttpSecurity;6import org.springframework.security.config.http.SessionCreationPolicy;7import org.springframework.security.web.SecurityFilterChain;8import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;9
10@Configuration11public class SecurityConfig {12
13 @Autowired14 private CustomOAuth2SuccessHandler customOAuth2SuccessHandler;15
16 @Autowired17 private OAuthValidationFilter oAuthValidationFilter;18
19 @Bean20 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {21 http22 .authorizeHttpRequests(auth -> auth23 .anyRequest().authenticated()24 )25 .sessionManagement(session -> session26 .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No session27 )28 .oauth2Login(oauth2 -> oauth229 .successHandler(customOAuth2SuccessHandler) // Use our custom handler30 )31 .addFilterBefore(oAuthValidationFilter, UsernamePasswordAuthenticationFilter.class);32
33 return http.build();34 }35}◆ Key Changes from Stateful Version
| Change | Stateful | Stateless |
|---|---|---|
| Session Policy | Default (IF_REQUIRED) | STATELESS |
| Success Handler | withDefaults() | customOAuth2SuccessHandler |
| Token Validation Filter | None | OAuthValidationFilter added |
Step 3 JWT Validation Filter
1// OAuthValidationFilter.java2import jakarta.servlet.FilterChain;3import jakarta.servlet.ServletException;4import jakarta.servlet.http.HttpServletRequest;5import jakarta.servlet.http.HttpServletResponse;6import org.springframework.beans.factory.annotation.Value;7import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;8import org.springframework.security.core.context.SecurityContextHolder;9import org.springframework.security.oauth2.jwt.Jwt;10import org.springframework.security.oauth2.jwt.JwtDecoder;11import org.springframework.security.oauth2.jwt.JwtDecoders;12import org.springframework.stereotype.Component;13import org.springframework.web.filter.OncePerRequestFilter;14
15import java.io.IOException;16import java.util.Collections;17
18@Component19public class OAuthValidationFilter extends OncePerRequestFilter {20
21 @Override22 protected void doFilterInternal(HttpServletRequest request,23 HttpServletResponse response,24 FilterChain filterChain)25 throws ServletException, IOException {26
27 // Step 1: Extract JWT from Authorization header28 String token = extractToken(request);29
30 if (token != null && isTokenValid(token)) {31 // Step 2: Set authentication in security context32 UsernamePasswordAuthenticationToken auth =33 new UsernamePasswordAuthenticationToken(34 "authenticated-user", null, Collections.emptyList()35 );36 SecurityContextHolder.getContext().setAuthentication(auth);37 }38
39 // Step 3: Continue filter chain40 filterChain.doFilter(request, response);41 }42
43 private String extractToken(HttpServletRequest request) {44 String header = request.getHeader("Authorization");45 if (header != null && header.startsWith("Bearer ")) {46 return header.substring(7); // Remove "Bearer " prefix47 }48 return null;49 }50
51 private boolean isTokenValid(String token) {52 try {53 // Step 1: Parse the token to find the issuer54 // (Without full verification — just to find which auth server issued it)55 String[] parts = token.split("\\.");56 String payload = new String(57 java.util.Base64.getUrlDecoder().decode(parts[1])58 );59
60 // Extract issuer from payload JSON61 // Simple extraction — in production use a JSON library62 String issuer = extractIssuer(payload);63
64 // Step 2: Use Spring's JwtDecoder — it fetches the public key from jwk-set-uri65 // based on the issuer, then verifies the token's signature66 JwtDecoder decoder = JwtDecoders.fromIssuerLocation(issuer);67 Jwt jwt = decoder.decode(token);68
69 // If decode succeeds without exception, the token is valid70 return true;71
72 } catch (Exception e) {73 return false;74 }75 }76
77 private String extractIssuer(String payloadJson) {78 // Simple JSON parsing for "iss" field79 // In production, use Jackson or Gson80 int issStart = payloadJson.indexOf("\"iss\":\"") + 7;81 int issEnd = payloadJson.indexOf("\"", issStart);82 return payloadJson.substring(issStart, issEnd);83 }84}◆ How Token Validation Works Internally
- Extract token from the
Authorization: Bearerheader. - Parse issuer from the JWT payload (without verifying signature yet).
JwtDecoders.fromIssuerLocation(issuer)— Spring's built-in utility that:
- Takes the issuer URL (e.g.,
https://gitlab.com). - Looks up the matching
jwk-set-urifromapplication.properties. - Fetches the public key from that JWK endpoint.
- Uses the public key to verify the JWT signature (asymmetric encryption — auth server signs with private key, we verify with public key).
- If
decoder.decode(token)succeeds, the token is valid. - Store authentication in
SecurityContextHolderso Spring Security treats the request as authenticated.
Step 4 Client Usage (Postman / Frontend)
Login:
- Open browser:
http://localhost:8080/login - Click an authorization server (GitLab / Auth0)
- Authenticate on the external server
- After redirect, Spring returns the ID token in the response body:
1 {2 "id_token": "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIi..."3 }Using the Token in Postman:
- Set header:
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9... - Call any API:
GET http://localhost:8080/user - Response:
Fetch the details successfully!
10. Complete Internal Flow Diagram
Stateless OAuth2 Flow (End-to-End)
11. Key Observations & Best Practices
Key Observations
- No user table needed — user identity is entirely managed by the Authorization Server (GitLab/Auth0). Your Spring Boot app never stores passwords.
- Registration ID matters — the key you use in
application.properties(e.g.,gitlab,auth0) becomes the registration ID. Spring uses it to build URLs like/oauth2/authorization/gitlab.
- Asymmetric signing — OIDC ID tokens are signed with the Authorization Server's private key and verified with its public key (fetched from
jwk-set-uri). This is RS256 (RSA + SHA-256), not HMAC.
- JwtDecoders handles complexity — Spring's
JwtDecoders.fromIssuerLocation()automatically discovers the JWK endpoint, fetches the key, and validates the token. You don't need to implement this manually.
- Session vs token — in stateful mode, after login, every request only checks the HTTP session. The token is not re-validated. In stateless mode, the token is validated on every request.
- ID token scope — the
openidscope triggers OIDC mode. Other scopes likeprofileandemailadd more claims to the ID token.
Best Practices
- Store Client Secret in environment variables or a secrets manager, never in code.
- Use RS256 (asymmetric) over HS256 (symmetric) for ID tokens in distributed systems.
- Implement token refresh logic for long-lived sessions using the refresh token.
- Store tokens in
OAuth2AuthorizedClientServicebacked by a database for production. - Validate
iss,aud, andexpclaims in your JWT validation. - Use
OncePerRequestFilterfor custom token filters to ensure they run exactly once per request.
12. Common Mistakes
Mistake 1 Forgetting `scope=openid`
1# WRONG - missing openid scope2spring.security.oauth2.client.registration.gitlab.scope=read_user3
4# CORRECT - use openid for OIDC authentication5spring.security.oauth2.client.registration.gitlab.scope=openidWithout openid, the auth server won't return an ID token.
Mistake 2 Using Form Login Instead of OAuth2 Login
1// WRONG2http.formLogin(withDefaults());3
4// CORRECT5http.oauth2Login(oauth2 -> oauth2.withDefaults());Mistake 3 Sending ID Token to Resource Server
The ID token is meant for the client app only. It proves user identity to your app. Don't send it to external resource servers — use the access token for that.
Mistake 4 Not Handling Session vs Stateless Mismatch
If you configure SessionCreationPolicy.STATELESS but don't add a token validation filter, every request will fail with 401 because there is no session to fall back on.
Mistake 5 Hardcoding the JWK URI Instead of Using `issuer-uri`
1# Less flexible — hardcoded JWK URI2spring.security.oauth2.client.provider.gitlab.jwk-set-uri=https://gitlab.com/oauth/discovery/keys3
4# Better — Spring auto-discovers all endpoints from the issuer5spring.security.oauth2.client.provider.gitlab.issuer-uri=https://gitlab.comUsing issuer-uri lets Spring auto-discover the token, authorization, and JWK endpoints via the OIDC discovery document (/.well-known/openid-configuration).
13. Interview Notes
Commonly Asked Questions
Q: What is the difference between OAuth2 and OIDC?
OAuth2 is for authorization (granting access to resources). OIDC is for authentication (verifying identity). OIDC is built on top of OAuth2 and adds the ID token — a JWT containing user identity claims.
Q: What is the Authorization Code Grant flow?
A two-step flow where the client first gets an authorization code, then exchanges it for a token. The code is short-lived and one-time-use. This adds security by keeping the access token out of the browser URL.
Q: Why is the Authorization Code flow more secure than Implicit Grant?
In Authorization Code flow, the token is returned to the backend server (via a POST to the token endpoint), not in the browser URL. Implicit Grant puts the token directly in the URL fragment — visible in browser history, logs, and referrer headers.
Q: What is an opaque token?
A token that is not self-contained — it's just a random string. Only the Authorization Server can validate it (by looking it up in its own database). Unlike JWT, the client cannot decode it.
Q: What is the JWK Set URI used for?
It's the endpoint where the Authorization Server publishes its public keys. Clients use these keys to verify the signature on JWT tokens without contacting the auth server for each request.
Q: How does Spring Boot know which filter to use for OAuth2?
When you addspring-boot-starter-oauth2-clientand call.oauth2Login(), Spring auto-configures a chain of filters includingOAuth2AuthorizationRequestRedirectFilterandOAuth2LoginAuthenticationFilter.
Q: What is the difference between stateful and stateless OAuth2 in Spring Boot?
Stateful:
Login creates an HTTP session. Subsequent requests check the session. Token not re-validated each time. Default behavior. Stateless: Login returns a token. Client sends token with every request. Server validates token each time. No session created.
Q: How do you customize behavior after successful OAuth2 login?
ImplementAuthenticationSuccessHandlerand register it via.oauth2Login(oauth2 -> oauth2.successHandler(myHandler)).
Q: Where does Spring store OAuth2 tokens by default?
In memory, viaInMemoryOAuth2AuthorizedClientService. Can be overridden with a database-backed implementation.
14. Summary Revision Bullets
- OAuth 2.0 = Open Authorization Framework — enables third-party access to user protected data without sharing passwords.
- Authorization Code Grant = most secure OAuth2 flow; uses a short-lived code exchanged for tokens by the backend.
- OIDC = OpenID Connect — built on OAuth2; adds the ID token (JWT) for authentication.
- OAuth2 purpose = Authorization (access to resources); OIDC purpose = Authentication (identity verification).
- ID Token = JWT meant for the client app only; contains minimal identity claims; never sent to resource server.
- Access Token = used to call resource server APIs; can be opaque or JWT.
- Opaque Token = random string; only the authorization server can validate it.
- JWK Set URI = endpoint hosting the public key used to verify JWT signatures.
- Three files needed for basic Spring Boot OAuth2:
pom.xml(dependency),application.properties(config),SecurityConfig.java(enable oauth2Login). - Key filters in Spring Security OAuth2:
DefaultLoginPageGeneratingFilter— renders the login pageOAuth2AuthorizationRequestRedirectFilter— redirects to auth serverOAuth2LoginAuthenticationFilter— handles the redirect URI callbackOidcAuthorizationCodeAuthenticationProvider— exchanges code for token- Stateful default — Spring creates an HTTP session after login; token not re-validated per request.
- Making it stateless — set
SessionCreationPolicy.STATELESS, add a custom success handler to return the token, add aOncePerRequestFilterto validate the token on each request. JwtDecoders.fromIssuerLocation(issuer)— Spring utility that auto-discovers and fetches the JWK public key and validates JWT signatures.- Registration IDs in
application.propertiesdrive the login page URLs:/oauth2/authorization/{registrationId}.
End of Study Guide
Mastery check
How well can you recall this?
Finished this lesson?