User Authentication ยท 5.4

๐ŸŽŸ๏ธ Token-Based Authentication (JWT & OAuth)

How modern web apps stay logged in without re-sending passwordsโฑ ~3 min

The Session Problem

HTTP is stateless โ€” each request is independent. After you log in, the server needs a way to know that subsequent requests come from you without requiring your password on every request. Two approaches exist: server-side sessions (server stores a session object and gives you a session ID cookie) or token-based auth (server issues a cryptographically signed token you send with every request).

JWT โ€” JSON Web Tokens

A JWT is a compact, URL-safe token with three base64url-encoded parts separated by dots: header.payload.signature.

json
// Header (base64url decoded)
{ "alg": "RS256", "typ": "JWT" }
// Payload (base64url decoded) โ€” the claims
{
"sub": "user_123",
"email": "alice@example.com",
"roles": ["user", "admin"],
"iat": 1704067200, // issued at
"exp": 1704070800 // expires at (1 hour later)
}
// Signature: RS256(base64(header) + '.' + base64(payload), private_key)
// Verification: verify signature with public key; check exp not in the past
โš  WarningJWT 'alg: none' vulnerability: the JWT spec allows an algorithm value of 'none', meaning no signature. Some libraries accept this and skip verification โ€” any attacker can forge a token with admin claims just by removing the signature and setting alg to none. Always verify: (1) signature is present, (2) algorithm matches what you expect (reject 'none'), (3) token is not expired, (4) issuer and audience are correct.

OAuth 2.0 โ€” Delegated Authorization

OAuth 2.0 is an authorization framework that lets you grant a third-party application limited access to your account without giving it your password. 'Sign in with Google' is OAuth 2.0 โ€” you authenticate to Google, Google issues a token that the app can use to access only the specific data you authorized (email, profile), and your Google password is never shared with the app.

RoleWho It IsExample
Resource OwnerThe userYou
ClientThird-party app requesting accessSpotify wanting your Google account
Authorization ServerIssues tokens after user consentGoogle's OAuth server
Resource ServerAPI holding protected dataGoogle People API (your contacts)
๐Ÿ’ก TipPKCE (Proof Key for Code Exchange) is mandatory for OAuth 2.0 in public clients (mobile apps, SPAs). Without PKCE, authorization codes can be intercepted and exchanged by an attacker. If you're implementing OAuth in a mobile or browser app, always use the PKCE flow.
๐Ÿง Quick Checkfirst try = +5 XP

The JWT 'alg: none' attack works when a serverโ€ฆ

โญ 0 XP๐Ÿ”ฅ 0 days