Authentication
Identity & Access

Authentication

A complete guide to Authentication (AuthN): verifying identity, the three authentication factors, tokens, sessions, OIDC, SAML, and Single Sign-On.

Imagine arriving at an airport border control checkpoint. When the customs officer asks who you are, you cannot simply say your name and walk through. The officer asks for an official passport containing your photo, date of birth, and security watermarks. The officer looks at your face, compares it to the photo, and verifies that the document is genuine. Once verified, the officer is confident that you are who you claim to be. In computing, this verification process is called Authentication (often shortened to AuthN). Authentication answers the fundamental question: 'Who are you, and can you prove it?' It is the front door of every digital system. Before a user, computer, or background service can access protected data, the system must verify their identity.

Definition

Authentication (AuthN) is the security process of verifying the claimed identity of a user, device, or system before granting access to an application or network.

Why It Matters

Without authentication, there is no way to protect privacy, secure financial transactions, or hold accounts accountable. Anyone could access any account simply by typing a web address or guessing a username. Authentication ties every action in a system to a verified user or service. If an unauthorized change occurs or data is deleted, audit logs allow security teams to see exactly which account made the change, when it occurred, and where the request originated.

How It Works

Authentication relies on verifying proof across one or more of three traditional authentication factors: 1. Something You Know (Knowledge Factor): Information that only the legitimate user should know, such as a password, passphrase, PIN number, or answer to a security prompt. Knowledge factors are common, but they can be guessed, stolen through phishing, or leaked in database breaches. 2. Something You Have (Possession Factor): A physical or digital item owned exclusively by the user, such as a smartphone running an authenticator app, a hardware security key (like a YubiKey), a smartcard, or a digital security certificate on a work laptop. 3. Something You Are (Inherence Factor / Biometrics): A physical or biological characteristic unique to the person, such as a fingerprint, facial scan, or voice pattern. 4. Sessions and Modern Single Sign-On (SSO): • Stateful Sessions: After verifying credentials, the server creates a random session ID stored in memory or a database (such as Redis) and sends it to the browser in a secure, HttpOnly cookie. On each visit, the browser presents the cookie to prove the user is logged in. • Stateless Tokens (JWTs): The server creates a signed JSON Web Token containing the user's ID and permissions. The token is cryptographically signed so downstream services can verify it without checking a central session database. • Federated Identity and Single Sign-On (SSO): Protocols like OpenID Connect (OIDC) and SAML allow users to log in once with a central Identity Provider (such as Google Workspace or Microsoft Entra) and access many business tools without retyping passwords.

Modern Web Authentication Architecture: OIDC Authorization Code Flow with PKCE

1. Authorization Request
The client app redirects the user to the Identity Provider (IdP) along with a cryptographic PKCE code challenge
2. User Authentication
The user logs in at the Identity Provider using primary credentials and a second authentication factor
3. Authorization Code Issued
The Identity Provider sends a temporary, short-lived authorization code back to the client application
4. Secure Token Exchange
The client backend exchanges the authorization code and original PKCE verifier directly with the Identity Provider
5. Tokens Issued
The Identity Provider verifies the code and issues a signed ID token (JWT) and access token
6. Secure Session Established
The client backend sets an encrypted, HttpOnly session cookie in the browser to maintain the login session

Key Points

  • Authentication verifies WHO you are; Authorization determines WHAT you are allowed to do.
  • The three classic factors are: Something you Know, Something you Have, and Something you Are.
  • Relying on passwords alone is fragile; modern security requires multi-factor authentication.
  • Do not store sensitive session tokens in browser localStorage because malicious scripts can access them during an XSS attack.
  • Federated authentication via OpenID Connect (OIDC) centralizes security management and provides seamless Single Sign-On (SSO).

Steps

  1. Use Transport Encryption (HTTPS/TLS)

    Always transmit login credentials over TLS to protect passwords and tokens from eavesdropping on the network.

  2. Hash Passwords Using Modern Algorithms

    Never store plaintext passwords. Hash passwords server-side using slow, memory-hard algorithms like Argon2id or bcrypt with unique cryptographic salts.

  3. Require Multi-Factor Authentication (MFA)

    Require users to provide at least two distinct factors (such as a password plus an authenticator app code or security key) for account access.

  4. Protect Session Cookies

    Store session tokens in cookies marked with HttpOnly (to prevent JavaScript theft), Secure (to restrict to HTTPS), and SameSite=Lax or Strict (to prevent CSRF).

  5. Enforce Rate Limiting on Login Forms

    Limit the number of login attempts allowed from an IP address or account to block automated brute-force attacks and credential stuffing.

Examples

The Secure Facility Checkpoint Analogy

Entering a secure data center often requires three separate proofs: 1. Typing a secret PIN code on a keypad (Something You Know), 2. Tapping an encrypted electronic badge on the reader (Something You Have), and 3. Scanning your fingerprint on a biometric reader (Something You Are). If someone steals your badge, they still cannot get in without your PIN and fingerprint.

Real-World Examples

The 23andMe Credential Stuffing Incident (2023)

Attackers used automated credential-stuffing tools to test lists of email addresses and passwords stolen from other websites against 23andMe login accounts. Because users reused passwords and accounts lacked mandatory multi-factor authentication, attackers gained access to millions of customer profiles.

The Golden SAML Identity Forgery Technique (2020)

During the SolarWinds investigation, researchers found that attackers who gained administrative access to federation servers were able to steal private SAML signing keys. With these keys, attackers could forge authentication tokens to impersonate any user across cloud services without needing their real passwords.

Technical Examples

Verifying JWT Tokens with RS256 Asymmetric Keys in Node.js / TypeScripttypescript
import jwt, { JwtPayload } from "jsonwebtoken";
import fs from "fs";

// Load Identity Provider's public key (PEM format)
const IDP_PUBLIC_KEY = fs.readFileSync("/etc/ssl/certs/idp_public_key.pem", "utf8");

export interface AuthenticatedUserPayload extends JwtPayload {
  sub: string;         // Subject: Unique User ID (e.g., "usr_94b8e21a")
  email: string;       // User's verified email address
  roles: string[];     // User roles assigned by Identity Provider
  iss: string;         // Token Issuer (e.g., "https://auth.company.com")
  aud: string;         // Intended Audience (e.g., "api://production-gateway")
}

// Express/Next.js authentication middleware
export function authenticateToken(req: any, res: any, next: any) {
  const authHeader = req.headers["authorization"];
  // Format: "Bearer <token_string>"
  const token = authHeader && authHeader.split(" ")[1];

  if (!token) {
    return res.status(401).json({
      error: "Unauthorized",
      message: "Authentication token missing from Authorization header.",
    });
  }

  try {
    // Validate cryptographic signature, expiration (exp), audience (aud), and issuer (iss)
    const verified = jwt.verify(token, IDP_PUBLIC_KEY, {
      algorithms: ["RS256"], // Strictly enforce asymmetric RS256; reject weak "none" or HS256
      issuer: "https://auth.company.com",
      audience: "api://production-gateway",
    }) as AuthenticatedUserPayload;

    // Attach verified identity to request context for downstream handlers
    req.user = verified;
    next();
  } catch (err: any) {
    return res.status(403).json({
      error: "Forbidden",
      message: "Authentication token verification failed: " + err.message,
    });
  }
}
This middleware checks the Authorization header, extracts the JWT, and verifies its cryptographic signature using the Identity Provider's public key. It confirms the token issuer and audience, while rejecting insecure algorithms like 'none'.

Stateful Session Authentication vs Stateless Token Authentication (JWT)

AspectStateful Session AuthenticationStateless Token Authentication (JWT)
Storage LocationServer memory or centralized cache (such as Redis)Client side (HttpOnly cookie or memory); no server state needed
ScalabilityRequires shared session storage across server clustersScales easily across microservices through cryptographic verification
Session RevocationImmediate: Delete the session key from the cacheRequires expiration management or a token revocation list
Data SizeSmall session ID string (typically 32 to 64 bytes)Larger self-contained payload (often 500 to 2,000 bytes)
Common Use CaseTraditional web apps and high-security banking portalsDistributed microservices, mobile APIs, and cross-domain SSO

Identity Federation: Comparing OIDC and SAML 2.0

Modern organizations use Identity Federation to allow employees to sign in once and access multiple cloud and internal tools: • OpenID Connect (OIDC): Built on OAuth 2.0 and JSON Web Tokens. It is lightweight, uses standard REST APIs over HTTPS, and is the preferred standard for modern web, cloud, and mobile applications. • SAML 2.0: An older, established standard based on XML documents and digital signatures. It is widely supported in enterprise software and corporate directories like Active Directory. Summary: Use OpenID Connect for new cloud applications and mobile projects, and use SAML 2.0 when integrating with existing enterprise directory infrastructure that requires it.

Advantages

  • Confirms True Identity: Establishes a verified basis for trust before exposing sensitive application features.
  • Supports Compliance Auditing: Required by standards like SOC 2, ISO 27001, and HIPAA to maintain user activity logs.
  • Enables Single Sign-On: Reduces password fatigue and lowers support costs by centralizing login management.

Limitations

  • Identity Provider Dependency: If a centralized Identity Provider suffers downtime, users cannot access connected services.
  • Token Storage Risks: If tokens are stored insecurely on the client, they can be vulnerable to cross-site scripting attacks.

Interview Questions

How do you handle token revocation when using stateless JWTs?

Because stateless JWTs are self-contained and verified locally, revoking them immediately without a central database requires specific patterns: 1. Keep access token lifespans short (5 to 15 minutes), 2. Pair them with refresh tokens stored in a database that can be revoked, 3. Maintain a fast revocation denylist of token IDs (jti) in memory or Redis, or 4. Use OpenID Connect back-channel logout notifications to tell services when a user logs out.

What is the JWT 'None' algorithm vulnerability?

In early JWT specifications, the algorithm header `alg: 'none'` was supported for unsigned tokens. In poorly written verification libraries, if a token specified `none`, the library would skip signature validation entirely. An attacker could edit their token claims (such as changing their role to admin), set `alg: 'none'`, and gain unauthorized access. Modern libraries protect against this by requiring developers to specify an explicit list of accepted algorithms (such as `['RS256']`).

Practice Questions

  1. Inspect the Network tab in your browser's developer tools on a website you are logged into: Check whether session cookies have the HttpOnly, Secure, and SameSite attributes enabled.
  2. Visit jwt.io, paste a sample token, and identify its header, payload claims (such as sub and exp), and signature section.