Authentication Quick Reference
Everything you need day‑to‑day – OAuth 2.0, OpenID Connect, JWT, and security.
Authentication vs Authorization
Authentication
- Who you are – verifying identity
- Login credentials (username/password, MFA, biometrics)
- Session tokens, JWT, OAuth tokens
- Question: "Are you who you say you are?"
Authorization
- What you can do – permissions and access
- RBAC (Role‑Based Access Control)
- ACL (Access Control Lists)
- Question: "What are you allowed to do?"
OAuth 2.0 Overview
Core Components
- Resource Owner – user (who owns the data)
- Client – application requesting access
- Authorization Server – issues tokens
- Resource Server – hosts protected resources
- Redirect URI – callback endpoint for OAuth flow
Token Types
- Access Token – short‑lived, used to access resources
- Refresh Token – long‑lived, used to get new access tokens
- ID Token – OpenID Connect, contains user info
- Authorization Code – intermediate code (used for token exchange)
OAuth 2.0 Grant Types (Flows)
| Flow | Use Case | Client Type | Security |
|---|---|---|---|
| Authorization Code | Web apps, mobile apps | Confidential (has client secret) | Highest (PKCE recommended) |
| Implicit | SPA (deprecated) | Public | Low (use Authorization Code with PKCE) |
| Client Credentials | Machine‑to‑machine (server‑to‑server) | Confidential | High |
| Resource Owner Password | Trusted apps (legacy) | Confidential | Low (avoid) |
| Refresh Token | Long‑lived access (session continuation) | All | Varies |
Authorization Code Flow (Recommended)
User (Resource Owner) Client App Authorization Server
| | |
|-- (1) Request resource --> | |
| | |
|<- (2) Redirect to Auth Server --------------------------|
| | |
|-- (3) Login + Consent --> | |
| | |
|<- (4) Auth Code redirect --| |
| | |
| |-- (5) Code + Secret --> |
| | |
| |- (6) Access + Refresh Token|
| | |
|<- (7) Access Resource --> | |
Authorization Code with PKCE (Recommended for Public Clients)
- PKCE – Proof Key for Code Exchange (RFC 7636)
- code_verifier – random string (43‑128 chars)
- code_challenge – hash of verifier (S256 or plain)
- Prevents authorization code interception attacks
- Required for mobile/SPA in OAuth 2.1
JWT (JSON Web Token)
JWT Structure
- Header – algorithm and token type
- Payload – claims (user info, permissions, expiration)
- Signature – cryptographic signature
- Format:
header.payload.signature - Base64Url encoded
Common Claims
- iss – issuer
- sub – subject (user ID)
- aud – audience (client ID)
- exp – expiration time (Unix timestamp)
- iat – issued at time
- nbf – not before time
- jti – JWT ID (unique identifier)
- scope – permissions
JWT Example
// Header { "alg": "HS256", "typ": "JWT" } // Payload { "sub": "1234567890", "name": "Alice", "iat": 1516239022, "exp": 1516242622 } // Signature HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret ) // Full JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyNDI2MjJ9. N3F0d2NhZGU1MzQ1Nj...
JWT Signing Algorithms
| Algorithm | Type | Key Size | Security | Use Case |
|---|---|---|---|---|
| HS256 | Symmetric (HMAC) | 256+ bits | Secure (if key kept secret) | Single server / internal |
| HS384 | Symmetric (HMAC) | 384+ bits | Very Secure | High security internal |
| HS512 | Symmetric (HMAC) | 512+ bits | Very Secure | High security internal |
| RS256 | Asymmetric (RSA) | 2048+ bits | Secure (private/public key) | Microservices, third‑party |
| ES256 | Asymmetric (ECDSA) | 256 bits (P‑256) | Very Secure (faster than RSA) | Modern apps, IoT |
| ES384 | Asymmetric (ECDSA) | 384 bits (P‑384) | Very High Security | High security |
| ES512 | Asymmetric (ECDSA) | 521 bits (P‑521) | Very High Security | Top security |
| none | None (unsecured) | – | Insecure | Testing only (never production) |
JWT in Code (Node.js)
const jwt = require('jsonwebtoken');
// Sign (HS256)
const token = jwt.sign(
{ sub: '123', name: 'Alice' },
'my-secret-key',
{ expiresIn: '1h', algorithm: 'HS256' }
);
// Verify
const decoded = jwt.verify(token, 'my-secret-key');
console.log(decoded); // { sub: '123', name: 'Alice', iat: ..., exp: ... }
// Sign (RS256)
const fs = require('fs');
const privateKey = fs.readFileSync('private.pem');
const token = jwt.sign({ sub: '123' }, privateKey, { algorithm: 'RS256' });
// Verify with public key
const publicKey = fs.readFileSync('public.pem');
const decoded = jwt.verify(token, publicKey, { algorithms: ['RS256'] });
JWT in Code (Python)
import jwt import datetime // Sign (HS256) payload = {'sub': '123', 'name': 'Alice'} secret = 'my-secret-key' token = jwt.encode(payload, secret, algorithm='HS256') // Verify decoded = jwt.decode(token, secret, algorithms=['HS256']) // Sign (RS256) with open('private.pem', 'r') as f: private_key = f.read() token = jwt.encode(payload, private_key, algorithm='RS256') // Verify with public key with open('public.pem', 'r') as f: public_key = f.read() decoded = jwt.decode(token, public_key, algorithms=['RS256'])
JWT in Code (Java)
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.security.Key; import java.util.Date; // Sign (HS256) Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); String token = Jwts.builder() .setSubject("123") .claim("name", "Alice") .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 3600000)) .signWith(key) .compact(); // Verify var claims = Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token) .getBody();
OpenID Connect (OIDC)
- OIDC – Identity layer on top of OAuth 2.0
- Adds authentication (user identity) to OAuth 2.0
- Returns ID Token (JWT) containing user info
- UserInfo endpoint – additional user profile data
- Standard claims: sub, name, email, picture, etc.
- Used by Google, Microsoft, Okta, Auth0, etc.
ID Token Example
{
"iss": "https://auth.example.com",
"sub": "user123",
"aud": "client456",
"exp": 1516242622,
"iat": 1516239022,
"nonce": "abc123",
"email": "alice@example.com",
"email_verified": true,
"name": "Alice Johnson"
}
Security Best Practices
JWT Best Practices
- Use short expiration (15‑60 minutes) for access tokens
- Use refresh tokens for long‑lived sessions
- Store JWT in HttpOnly, Secure cookies (not localStorage)
- Use strong signing algorithms (RS256, ES256, HS256 with long key)
- Validate iss, aud, exp claims
- Use jti (JWT ID) to prevent replay attacks
- Rotate keys regularly
OAuth Best Practices
- Use Authorization Code + PKCE for SPAs and mobile
- Store client secrets securely (never in frontend)
- Use redirect URIs whitelist
- Use state parameter to prevent CSRF
- Use scope for least privilege
- Implement token revocation endpoint
- Use OAuth 2.1 (modern standard)
Token Storage (Important)
| Storage | XSS | CSRF | Visibility | Recommendation |
|---|---|---|---|---|
| HttpOnly Cookie | Protected | Vulnerable | Server‑side only | Recommended (with SameSite) |
| localStorage | Vulnerable | Protected (with fetch) | Client‑side | Avoid for tokens |
| sessionStorage | Vulnerable | Protected | Client‑side (per tab) | Avoid for tokens |
| Memory | Protected | Protected | Client‑side | Best for SPAs (with refresh) |
Common Attacks & Mitigations
| Attack | Description | Mitigation |
|---|---|---|
| Token Leakage | JWT exposed in URL, logs, or storage | Use Authorization header, HttpOnly cookies |
| Replay Attack | Token captured and reused | Short expiry, jti claim, refresh rotation |
| CSRF | Cross‑Site Request Forgery | SameSite cookies, CSRF token, state param |
| XSS | Cross‑Site Scripting steals tokens | HttpOnly cookies, CSP, sanitization |
| Man‑in‑the‑Middle | Token intercepted | HTTPS, TLS 1.2+, certificate pinning |
| Algorithm Confusion | Forcing HS256 with RSA public key | Validate algorithm, use `algorithms` in verify |
| None Algorithm Attack | Using `alg: none` | Reject `none` algorithm |
Common Libraries
JWT Libraries
- Node.js – `jsonwebtoken`
- Python – `PyJWT`
- Java – `jjwt` (Java JWT)
- Go – `golang-jwt/jwt`
- Rust – `jsonwebtoken`
- .NET – `Microsoft.IdentityModel.JsonWebTokens`
OAuth/OIDC Libraries
- Node.js – `passport`, `oauth2‑server`
- Python – `Authlib`, `python‑oauth2`
- Java – `Spring Security`
- Go – `golang.org/x/oauth2`
- Identity Providers – Keycloak, Auth0, Okta, Google Identity
OAuth 2.0 Scopes
| Scope | Description |
|---|---|
openid |
Request ID token (OpenID Connect) |
profile |
Read user profile info |
email |
Read user email address |
offline_access |
Request refresh token |
read:users |
Read user data (custom) |
write:users |
Write user data (custom) |
📌 Quick Reference
OAuth 2.0: Authorization Code (recommended), Implicit (deprecated), Client Credentials (M2M)
JWT: Header.Payload.Signature, claims: iss, sub, aud, exp, iat
Algorithms: HS256 (sym), RS256 (asym), ES256 (asym, ECDSA)
PKCE: Required for public clients (SPAs, mobile) – uses code_verifier + code_challenge
Storage: HttpOnly Secure cookies (recommended), avoid localStorage for tokens
OpenID Connect: Adds authentication (ID token) to OAuth 2.0
Security: Validate signatures, check exp/aud/iss, use short expiry, rotate keys
JWT: Header.Payload.Signature, claims: iss, sub, aud, exp, iat
Algorithms: HS256 (sym), RS256 (asym), ES256 (asym, ECDSA)
PKCE: Required for public clients (SPAs, mobile) – uses code_verifier + code_challenge
Storage: HttpOnly Secure cookies (recommended), avoid localStorage for tokens
OpenID Connect: Adds authentication (ID token) to OAuth 2.0
Security: Validate signatures, check exp/aud/iss, use short expiry, rotate keys