Back to JWT: Structure, Validation, Storage
Q7Question 7 of 7

JWT vs OAuth 2.0: Token Format vs Authorization Framework

Answer: JWT is a token format that defines how claims are structured and signed; OAuth 2.0 is an authorization framework that defines how clients obtain and use tokens; they solve different problems and can be used together or independently.

Key Concepts
  • JWT is a token FORMAT (header.payload.signature) that represents claims in a compact, signed structure.
  • OAuth 2.0 is an authorization FRAMEWORK that defines flows for obtaining access tokens (Authorization Code, Client Credentials, etc.).
  • OAuth 2.0 can issue JWTs as access tokens, but it can also issue opaque tokens; JWT is not required for OAuth 2.0.
  • JWT can be used without OAuth 2.0 (e.g., a custom login endpoint that issues JWTs directly).
  • The common interview mistake is saying OAuth 2.0 IS a token or saying all OAuth tokens are JWTs.
  • In practice, they work together: OAuth 2.0 defines how the token is obtained, JWT defines the token's structure and how it is validated.

Definition

JWT is a token format that defines how claims are structured and signed; OAuth 2.0 is an authorization framework that defines how clients obtain and use tokens; they solve different problems and can be used together or independently.
  • 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:

TEXT
header.payload.signature

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJyYWplc2giLCJyb2xlIjoiVEVMTEVSIiwiZXhwIjoxNzMxNTAwMDAwfQ.
<signature-bytes>

The header specifies the algorithm:

JSON
{ "alg": "RS256", "typ": "JWT" }

The payload contains claims:

JSON
{
  "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:

RoleExample in banking
Resource OwnerPriya (the bank customer)
ClientMobile banking app
Authorization ServerNational Bank Identity Service
Resource ServerAccount API, Transfer API

And multiple flows:

FlowWhen to use
Authorization Code + PKCEWeb/mobile apps where a user logs in
Client CredentialsService-to-service (no user involved)
Refresh TokenGetting 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?

AspectJWTOAuth 2.0
What is itA token format (RFC 7519)An authorization framework (RFC 6749)
DefinesHow claims are structured and signedHow clients obtain and use access tokens
Token formatAlways JWTJWT, opaque, or any format
Can be used aloneYes (custom login endpoint issues JWT)Yes (with opaque tokens, no JWT needed)
ValidationLocal: verify signature + claimsDepends: local (JWT) or introspection (opaque)
RolesNone (just a token)Client, Resource Owner, Auth Server, Resource Server
FlowsNone (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:

  1. The client authenticates with the OAuth 2.0 authorization server.
  2. The authorization server issues an access token in JWT format.
  3. The client sends the JWT in the Authorization header.
  4. The resource server validates the JWT signature and claims locally.
JAVA
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();
    }
}
YAML
# 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:

JAVA
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:

YAML
# 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 tokenOpaque access token
Self-contained: validated locallyRequires introspection call to auth server
Larger token sizeSmall token size
Revocation is harder (token valid until expiry)Revocation is immediate (introspection returns "active: false")
No network call for validationNetwork call per request (or cached)

What are common interview mistakes?

  1. Saying "OAuth 2.0 is a token" – it is a framework, not a token.
  2. Saying "All OAuth tokens are JWTs" – they can be opaque.
  3. Saying "JWT is an authentication protocol" – it is a token format; it does not define how you log in.
  4. 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

DIAGRAM
┌──────────────────────────────────────────────────┐
│               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.

---

Share
Use ← → arrow keys to navigate