OAuth vs JWT

Authorization protocol vs token format

OAuth and JWT are often mentioned together but operate at different levels. OAuth is an authorization framework that defines how applications obtain limited access to user accounts, while JWT (JSON Web Token) is a token format for securely transmitting claims between parties. OAuth often uses JWTs as its token format, but they are not interchangeable concepts.

OAuth

OAuth (specifically OAuth 2.0) is an authorization framework standardized in 2012. It allows third-party applications to obtain limited access to a user's resources without exposing their password. OAuth defines flows (authorization code, client credentials, etc.) for different scenarios. When you click 'Sign in with Google,' you are using OAuth. It separates the concerns of authentication, authorization, and resource access.

JWT

JWT (JSON Web Token) is a compact, URL-safe token format defined in RFC 7519. A JWT consists of three Base64-encoded parts: a header (algorithm and type), a payload (claims like user ID, expiration, roles), and a signature. JWTs are self-contained, meaning the server can validate them without a database lookup. They are commonly used as bearer tokens in API authentication.

Key Differences

- **Level of abstraction**: OAuth is a protocol/framework defining authorization flows. JWT is a token format for encoding and transmitting claims. - **Scope**: OAuth handles the entire authorization lifecycle (consent, token issuance, token refresh). JWT just defines how to structure and sign a token. - **Statefulness**: OAuth can use opaque tokens that require server-side lookup. JWTs are stateless and self-contained. - **Revocation**: OAuth supports token revocation endpoints. Revoking a JWT before expiry is harder because it is stateless (requires blocklists). - **Usage**: OAuth is used when third-party apps need access to user resources. JWTs are used whenever you need a signed, portable claim (session tokens, API auth, inter-service communication). - **Relationship**: OAuth often uses JWTs as the format for access tokens. They are complementary, not alternatives.

When to Use Each

**Use OAuth** when you need to authorize third-party applications to access user data, want to implement 'Sign in with X' functionality, or need delegated authorization with scoped permissions. **Use JWT** when you need stateless authentication tokens for your own APIs, want to pass signed claims between services, or need a compact token format that can be verified without hitting a database.

Analogy

**OAuth** is like the process of getting a hotel key card: you check in at the front desk, prove your identity, and receive a card granting access to specific rooms and amenities. **JWT** is the key card itself: a compact, encoded object containing your room number, checkout date, and access permissions, verifiable by any door lock without calling the front desk.