Authentication Basics
Master the complete web identity lifecycle: Authentication vs Authorization, slow password hashing (Argon2id/bcrypt), secure session cookies, MFA, Passkeys, and route protection.
The Foundation of Web Trust
Every web platform that handles user data, private dashboards, or transactions requires a reliable mechanism to identify users and safeguard their sessions.
Modern web authentication combines cryptographic hashing, stateless transport layers, secure cookie flags, and authorization policies to protect users against unauthorized access, data theft, and impersonation.
Authentication (AuthN) vs. Authorization (AuthZ)
“Who are you?”
The process of verifying the identity of a user or system attempting to access the platform (e.g. email + password, passkey, or OAuth token).
“What are you permitted to do?”
The process of checking whether an authenticated user has the necessary permissions/roles to perform an action or view a resource.
Password Hashing vs. Reversible Encryption
Reversible encryption requires a secret key. If the key or server is compromised, all user passwords are exposed. Passwords must ALWAYS be stored using one-way slow cryptographic password-hashing algorithms with unique random salts.
OWASP Recommended Algorithms:
| Algorithm | Type | OWASP Status | Why It Is Preferred |
|---|---|---|---|
| Argon2id | Memory-hard slow hash | Top Recommended | Resistant to GPU, ASIC, and side-channel cache attacks. Winner of Password Hashing Competition. |
| bcrypt | Adaptive work-factor hash | Recommended | Battle-tested over 25+ years. Configurable computational work factor. |
| PBKDF2 | Key derivation function | Acceptable | FIPS compliant. Requires high iteration count (600,000+). |
| MD5 / SHA-256 | General-purpose fast hash | BANNED for passwords | Too fast. GPUs can compute billions of SHA-256 hashes per second to brute force passwords. |
Sessions and Secure Cookie Flags
Because HTTP is a stateless protocol, the server issues a session token upon successful login. For browser applications, storing this token in an HTTP Cookie with strict security flags is the industry standard:
Set-Cookie: session_id=s_9f82kd01a89c; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=604800;
HttpOnly
Blocks client-side JavaScript (like document.cookie) from reading the session token. Stops cross-site scripting session theft.
Secure
Ensures the browser only transmits the cookie over encrypted HTTPS connections, preventing plaintext network eavesdropping.
SameSite=Lax
Prevents the cookie from being sent along with third-party cross-site requests, neutralizing CSRF exploits.
Modern Authentication Methods
Password + Salted Hash
Knowledge factor. User enters password; server verifies against Argon2id/bcrypt hash.
MFA / 2FA (TOTP)
Combines knowledge factor with possession factor (6-digit authenticator app token via RFC 6238).
Social Login (OAuth 2.0 / OIDC)
Delegates identity verification to trusted providers (Google, GitHub, Apple) via signed ID tokens.
Passkeys (FIDO2 / WebAuthn)
Phishing-resistant asymmetric public-key cryptography unlocked via device biometrics (Touch ID, Face ID).
Route Protection & Security Essentials
In modern frameworks like Next.js, authentication checks are executed server-side via Edge Middleware before protected route rendering:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(req: NextRequest) {
const sessionToken = req.cookies.get('session_token')?.value;
if (!sessionToken && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/settings/:path*'],
};Authentication Best Practices & Checklist
- Always enforce HTTPS on all routes.
- Hash passwords with Argon2id or bcrypt with unique per-user salt.
- Store session tokens in
HttpOnly; Secure; SameSite=Laxcookies. - Apply Rate Limiting to login, register, and password-reset endpoints.
- Use cryptographically random, short-lived (15 min) single-use tokens for password resets.
- Support Multi-Factor Authentication (TOTP / WebAuthn Passkeys).
🔥 Live Interactive — Authentication Flow Simulator
Inspect the end-to-end authentication lifecycle across Browser, Server, Database, and Session layers.
1. User Registration & Password Hashing
The browser submits credentials over TLS. The server salts and hashes the password using Argon2id or bcrypt before saving to the database.
// Server-Side Password Hashing
const salt = crypto.randomBytes(16);
const passwordHash = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3
});
await db.users.create({ email, passwordHash });Answer these real-world architectural scenarios to reinforce your understanding.