Code-Memo

Authentication & Authorization

Authentication vs authorization

  1. Authentication answers “who are you?” (identity proof: password, token, mTLS).
  2. Authorization answers “what may you do?” (roles, scopes, policies on resources).
  3. Mixing the two in error messages confuses clients; return 401 vs 403 consistently with your policy.

API keys

  1. Simple shared secrets in headers or query params; easy for scripts and integrations.
  2. Weaknesses: broad access if leaked, rotation pain; prefer scoped keys and rate limits.
  3. Often combined with IP allowlists for server-to-server calls.

JWT (JSON Web Tokens)

  1. Self-contained signed tokens; can carry claims (sub, exp, scopes) without hitting a session store every time.
  2. Risks: stolen tokens, difficulty revoking without a denylist, algorithm confusion if misconfigured (alg=none).
  3. Prefer short lifetimes, refresh tokens with rotation, and explicit audience/issuer checks.

OAuth2 overview

  1. Delegated authorization framework: resource owner, client, authorization server, resource server.
  2. Common flows: Authorization Code (+ PKCE for public clients), Client Credentials for machine-to-machine.
  3. OAuth solves consent and token issuance, not your full domain authorization model.

Session-based auth vs token-based auth

  1. Sessions: server stores session id; client holds cookie; simple revocation; needs sticky sessions or shared store at scale.
  2. Tokens: client presents bearer token each call; scales horizontally; plan revocation and clock skew.
  3. Hybrid patterns (session + API tokens) are common; document cookie attributes (Secure, HttpOnly, SameSite).