Definition
- JWT (JSON Web Token) – a compact, URL-safe token format with three Base64URL-encoded parts: header (algorithm), payload (claims like sub, exp, iss), and signature (HMAC or RSA).
- OAuth 2.0 – an authorization framework that defines roles (client, resource server, authorization server, resource owner) and flows (Authorization Code, Client Credentials, Implicit, Resource Owner Password) for delegated access.
- Access token – the credential OAuth 2.0 issues; it can be a JWT (self-contained, verified locally) or an opaque string (verified by calling the authorization server's introspection endpoint).
- They are complementary – OAuth 2.0 answers "how do you get a token?" and JWT answers "what does the token look like?"
Think of a bank. OAuth 2.0 is the process for getting an access card: you visit the reception (authorization server), prove your identity, state which areas you need access to, and receive a card. JWT is the format of that card: it has your name, your authorized zones, and a tamper-proof hologram (signature). The card could also be a plain numbered badge (opaque token) that the guard has to look up in a book. The process of getting the card (OAuth 2.0) and the format of the card (JWT) are separate concerns.
Understanding the Concepts
What is JWT?
JWT is a token format defined by RFC 7519. It represents claims as a JSON object that is digitally signed.
A JWT has three parts separated by dots:
header.payload.signature
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJyYWplc2giLCJyb2xlIjoiVEVMTEVSIiwiZXhwIjoxNzMxNTAwMDAwfQ.
<signature-bytes>
The header specifies the algorithm:
{ "alg": "RS256", "typ": "JWT" }
The payload contains claims:
{
"sub": "rajesh",
"role": "TELLER",
"branch": "MUMBAI-001",
"exp": 1731500000,
"iss": "https://auth.nationalbank.in"
}
The signature is computed over the header and payload using a private key (RSA/ECDSA) or a shared secret (HMAC).
JWT is self-contained: a resource server can validate it locally using the issuer's public key without calling any external service.
What is OAuth 2.0?
OAuth 2.0 is an authorization framework defined by RFC 6749. It defines how a client application can obtain limited access to a user's resources without knowing the user's password.
OAuth 2.0 defines four roles:
| Role | Example in banking |
|---|---|
| Resource Owner | Priya (the bank customer) |
| Client | Mobile banking app |
| Authorization Server | National Bank Identity Service |
| Resource Server | Account API, Transfer API |
And multiple flows:
| Flow | When to use |
|---|---|
| Authorization Code + PKCE | Web/mobile apps where a user logs in |
| Client Credentials | Service-to-service (no user involved) |
| Refresh Token | Getting a new access token without re-login |
OAuth 2.0 does NOT define the token format. The access token can be a JWT, an opaque string, or any other format the authorization server chooses.
How are they different?
| Aspect | JWT | OAuth 2.0 |
|---|---|---|
| What is it | A token format (RFC 7519) | An authorization framework (RFC 6749) |
| Defines | How claims are structured and signed | How clients obtain and use access tokens |
| Token format | Always JWT | JWT, opaque, or any format |
| Can be used alone | Yes (custom login endpoint issues JWT) | Yes (with opaque tokens, no JWT needed) |
| Validation | Local: verify signature + claims | Depends: local (JWT) or introspection (opaque) |
| Roles | None (just a token) | Client, Resource Owner, Auth Server, Resource Server |
| Flows | None (just encode/decode/verify) | Authorization Code, Client Credentials, etc. |
How do they work together?
In most production systems, OAuth 2.0 and JWT work together:
- The client authenticates with the OAuth 2.0 authorization server.
- The authorization server issues an access token in JWT format.
- The client sends the JWT in the Authorization header.
- The resource server validates the JWT signature and claims locally.
package com.bank.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class BankResourceServerConfig {
// OAuth 2.0 resource server that validates JWT access tokens
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.sessionManagement(sess -> sess
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/accounts/**").hasAuthority("SCOPE_accounts.read")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}
}
# application.yml: tells Spring where to find the JWT issuer's public keys
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.nationalbank.in
Here, OAuth 2.0 defines the flow (how the token was obtained). JWT defines the format (how the token is structured and validated).
Can you use JWT without OAuth 2.0?
Yes. A simple banking application might issue JWTs from a custom login endpoint without implementing the full OAuth 2.0 framework:
package com.bank.controller;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.Map;
@RestController
public class LoginController {
private final AuthenticationManager authManager;
private final String secretKey = "bank-secret-key-min-256-bits-long-for-hmac";
public LoginController(AuthenticationManager authManager) {
this.authManager = authManager;
}
@PostMapping("/login")
public Map<String, String> login(@RequestBody LoginRequest request) {
Authentication auth = authManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.username(), request.password()
)
);
String token = Jwts.builder()
.setSubject(auth.getName())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 3600000))
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes())
.compact();
return Map.of("token", token);
}
}
This works but has limitations: no token refresh, no scopes, no standard discovery endpoints, no token revocation. For production banking systems, use a proper OAuth 2.0 authorization server.
Can you use OAuth 2.0 without JWT?
Yes. OAuth 2.0 can issue opaque access tokens (random strings). The resource server validates them by calling the authorization server's introspection endpoint:
# Opaque token configuration
spring:
security:
oauth2:
resourceserver:
opaquetoken:
introspection-uri: https://auth.nationalbank.in/introspect
client-id: account-api
client-secret: ${INTROSPECTION_SECRET}
| JWT access token | Opaque access token |
|---|---|
| Self-contained: validated locally | Requires introspection call to auth server |
| Larger token size | Small token size |
| Revocation is harder (token valid until expiry) | Revocation is immediate (introspection returns "active: false") |
| No network call for validation | Network call per request (or cached) |
What are common interview mistakes?
- Saying "OAuth 2.0 is a token" – it is a framework, not a token.
- Saying "All OAuth tokens are JWTs" – they can be opaque.
- Saying "JWT is an authentication protocol" – it is a token format; it does not define how you log in.
- Confusing OAuth 2.0 with OpenID Connect – OAuth 2.0 is for authorization (what can you do?), OIDC adds authentication (who are you?).
What should a senior engineer know?
- A JWT access token is often preferred for microservices because each service can validate the token locally without calling the authorization server, reducing latency and removing a single point of failure.
- For high-security banking applications, consider using opaque tokens with introspection for sensitive operations (fund transfers) where immediate revocation is critical, and JWT tokens for read-only operations (balance check) where performance matters.
- The JWT
aud(audience) claim should match the resource server's identifier. Without audience validation, a token meant for one API could be used on another. - Spring Security's
oauth2ResourceServer().jwt()automatically fetches the issuer's public keys via the JWKS endpoint discovered from the issuer-uri.
Visual Overview
┌──────────────────────────────────────────────────┐
│ OAuth 2.0 + JWT Together │
└──────────────────────────────────────────────────┘
Step 1: Client authenticates via OAuth 2.0 flow
Mobile App Auth Server
(Client) (National Bank Identity)
│ │
│── Authorization Request ──→│
│ (Code + PKCE) │
│ │
│←── Authorization Code ─────│
│ │
│── Token Exchange ─────────→│
│ (code + verifier) │
│ │
│←── JWT Access Token ───────│
│ (header.payload.sig) │
Step 2: Client uses JWT to access resource
Mobile App Account API
│ (Resource Server)
│── GET /api/accounts ──→│
│ Authorization: Bearer│
│ eyJhbG... │
│ │
│ ┌────┴────────────┐
│ │ Validate JWT: │
│ │ 1. Verify sig │
│ │ 2. Check exp │
│ │ 3. Check iss │
│ │ 4. Check aud │
│ │ 5. Check scope │
│ └────┬────────────┘
│ │
│←── 200 OK + data ──────│
Key Takeaway
JWT and OAuth 2.0 are two of the most commonly confused concepts in security interviews. JWT is a token format: it defines how to structure claims in a compact, signed JSON object. OAuth 2.0 is an authorization framework: it defines the flows and roles for obtaining access tokens without sharing passwords.
They often work together. An OAuth 2.0 authorization server issues an access token, and that token happens to be a JWT. The client sends the JWT to the resource server, which validates the signature and claims locally. But they can also work independently. A simple application can issue JWTs from a custom login endpoint without OAuth 2.0. An OAuth 2.0 system can issue opaque tokens instead of JWTs.
In National Bank of India's mobile banking app, Priya authenticates through the OAuth 2.0 Authorization Code flow with PKCE. The authorization server issues a JWT access token containing her customer ID, scopes (accounts.read, transfers.write), and an expiration time. The Account API validates the JWT locally using the authorization server's public key. No introspection call is needed, which keeps the API fast even under heavy load.
The practical difference matters for architecture decisions. JWT tokens are self-contained and validated locally, making them fast but harder to revoke. Opaque tokens require an introspection call, making revocation immediate but adding network latency. Senior engineers choose based on the trade-off between performance and revocation requirements.
The one sentence to remember: JWT is a token FORMAT that defines structure and signature; OAuth 2.0 is an authorization FRAMEWORK that defines how tokens are obtained; they solve different problems and work together in most production systems.
---