Authentication — Cheat Sheet

Tags: auth, jwt, oauth2, session, security, webdev

Level: intermediate

TL;DR: Distinzione tra autenticazione e autorizzazione, gestione sessioni stateful vs token stateless (JWT), flussi OAuth2/OIDC e best practice di sicurezza per token e password.

Key concepts

Authentication verifies identity (who you are); authorization verifies permissions (what you can do).

Session-based authentication stores session data server-side and maps it via a cookie ID.

Token-based authentication (JWT) encodes claims client-side, verified cryptographically by the server.

JWT structure consists of three base64url parts: header (algorithm), payload (claims), and signature.

JWT signature prevents tampering; it does not encrypt payload contents.

Short-lived access tokens limit blast radius; long-lived refresh tokens handle renewal securely.

OAuth 2.0 is an authorization framework allowing third-party access without sharing user credentials.

OpenID Connect (OIDC) is an identity layer built on OAuth 2.0 supplying an id_token.

OAuth 2.0 Authorization Code Flow with PKCE is the standard pattern for Single Page and mobile apps.

Passwords must be hashed using salted, compute-heavy key derivation functions like Argon2, bcrypt, or scrypt.

Typical questions and ready answers

Q: How do you choose between cookie sessions and JWT for a web application?R: I evaluate architectural requirements: for traditional monolithic apps, server-backed sessions with HttpOnly cookies provide instant revocation and lower complexity. For distributed microservices, APIs, or cross-domain clients, JWTs enable stateless verification across services without shared session databases.

Q: Where should tokens be stored in a Single Page Application?R: Storing access tokens in memory (or a closure) and refresh tokens in a SameSite=Strict, HttpOnly, Secure cookie protects against XSS token harvesting and mitigates CSRF risks.

Q: How do you handle token revocation with stateless JWTs?R: I keep access token lifetimes very short (e.g., 5-15 minutes) and implement revocation at the refresh token level via database blocklists or token family rotation.

Pitfalls and common mistakes

Storing sensitive personal data or secrets inside an unencrypted JWT payload.

Saving tokens in localStorage, exposing credentials to extraction via Cross-Site Scripting (XSS).

Accepting the none algorithm in JWT verification libraries.

Relying on fast hashing algorithms like MD5, SHA-1, or plain SHA-256 for password storage.

Implementing OAuth 2.0 Implicit Flow instead of Authorization Code Flow with PKCE.

Omitting CSRF protection when using session cookies without modern SameSite flags.

Snippets and commandsTypeScript

// Express.js middleware validating Bearer JWT and verifying signature
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

interface AuthPayload {
  userId: string;
  role: string;
}

export function authenticateToken(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Access token missing' });
  }

  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string, (err, decoded) => {
    if (err) {
      return res.status(403).json({ error: 'Invalid or expired token' });
    }
    req.user = decoded as AuthPayload;
    next();
  });
}

Bash

# Generate a cryptographically strong 256-bit secret key for signing
openssl rand -base64 32

To review

[ ] OAuth 2.0 grant types: Authorization Code with PKCE vs Client Credentials

[ ] Refresh token rotation and automatic reuse detection

[ ] Cookie attributes: HttpOnly, Secure, SameSite=Lax/Strict

[ ] Multi-Factor Authentication (TOTP RFC 6238 and WebAuthn/FIDO2)

[x] Differences between symmetric (HS256) and asymmetric (RS256) JWT signing

References

RFC 7519: JSON Web Token (JWT)

RFC 6749: The OAuth 2.0 Authorization Framework

RFC 7636: Proof Key for Code Exchange by OAuth Public Clients (PKCE)

OWASP Cheat Sheet Series: Authentication and Password Storage

Jarvis Interviews
Jarvis