Web Security 08 🛡️ Authentication, Passwords & Passkeys — Implementing Argon2id hashing, MFA, and phishing-resistant WebAuthn/Passkeys
Authentication is the fundamental process of verifying a user’s identity before granting access to protected resources. Historically, this relied almost exclusively on passwords—shared secrets between the user and the server. However, as compute power scaled and data breaches became more frequent, the industry moved from simple storage to cryptographic hashing, then to salt-based systems, and finally to modern memory-hard functions like Argon2. Even with perfect hashing, passwords remain vulnerable to phishing, credential stuffing, and social engineering, leading to the necessity of multi-layer defenses.
This chapter explores the modern landscape of secure authentication, starting with the implementation of Argon2id, the current industry gold standard for password hashing. We will examine the transition from traditional Multi-Factor Authentication (MFA) methods like TOTP to the phishing-resistant world of WebAuthn and Passkeys. By the end, you will understand how to construct an authentication pipeline that remains resilient even if the database is compromised or the user is targeted by a phishing campaign.
Key point: Secure authentication requires a defense-in-depth approach where passwords are never stored but hashed using memory-hard functions like Argon2id, supplemented by phishing-resistant MFA or replaced entirely by WebAuthn/Passkeys that leverage public-key cryptography.
Why X exists
1. The offline cracking problem.
When a database is breached, attackers obtain the list of stored credentials. If passwords are stored in plain text or using fast hashes like MD5 or SHA-1, attackers can use high-end GPUs or ASICs to test billions of combinations per second. Modern hashing algorithms exist to make each individual guess prohibitively expensive in terms of time and hardware resources.
2. The credential stuffing problem.
Users notoriously reuse passwords across different platforms. If one site is breached, attackers use those credentials to gain access to other services. Advanced authentication mechanisms like MFA exist to ensure that even if a password is known, the attacker cannot gain access without a second, time-sensitive, or hardware-bound factor.
3. The phishing problem.
Traditional authentication methods, including passwords and even SMS or TOTP-based MFA, are vulnerable to phishing. An attacker can create a fake login page that proxies the user’s credentials and MFA code in real-time. WebAuthn exists to solve this by binding the authentication credential to the specific origin (domain), making it cryptographically impossible to use a credential on a rogue site.
4. The side-channel problem.
Simple hashing implementations can be vulnerable to timing attacks, where an attacker determines information about a password based on how long the server takes to process a request. Modern algorithms like Argon2id are specifically designed to provide side-channel resistance, ensuring that execution time does not leak sensitive information.
5. The hardware acceleration problem.
Traditional hashes like Bcrypt are compute-intensive but don’t use much memory. This allows attackers to use specialized hardware (FPGAs/ASICs) that can run many instances in parallel. Argon2 exists to be “memory-hard,” requiring a significant amount of RAM for each hash, which makes custom hardware attacks much more expensive and less effective.
a. Argon2id: The Gold Standard for Hashing
Argon2 was the winner of the Password Hashing Competition (PHC) in 2015. Unlike Bcrypt or Scrypt, Argon2id provides the best balance of resistance against GPU/ASIC attacks and side-channel timing attacks. It uses three main parameters to tune security: Time Cost (iterations), Memory Cost (RAM usage), and Parallelism (threads).
import argon2 from 'argon2';
// Hashing a password with modern parameters
async function hashPassword(password: string) {
try {
const hash = await argon2.hash(password, {
type: argon2.argon2id, // Argon2id is preferred
memoryCost: 65536, // 64 MB of RAM
timeCost: 3, // 3 iterations
parallelism: 4 // 4 threads
});
return hash;
} catch (err) {
console.error('Hashing failed', err);
}
}
The resulting hash string includes the algorithm, version, parameters, salt, and the hash itself, all encoded into a single string. This format allows you to upgrade your security parameters over time; the server can detect that an old hash used “timeCost: 1” and automatically re-hash the password the next time the user logs in.
// Verifying a password
async function verifyUser(password: string, storedHash: string) {
const isMatch = await argon2.verify(storedHash, password);
if (isMatch) {
// Check if the hash parameters are outdated
if (argon2.needsRehash(storedHash, { memoryCost: 65536, timeCost: 3 })) {
// Re-hash and update database
}
return true;
}
return false;
}
By using Argon2id, you ensure that even if your database is leaked, the “cost” for an attacker to crack a single password is significantly higher than with older algorithms, providing users with a vital window of time to change their credentials.
b. Multi-Factor Authentication (MFA) Strategies
MFA requires the user to provide two or more “factors” from different categories: something you know (password), something you have (phone, security key), or something you are (biometrics).
- TOTP (Time-based One-Time Password): The most common MFA. A shared secret is generated and stored as a QR code. Apps like Google Authenticator use this secret and the current time to generate a 6-digit code every 30 seconds.
- SMS/Email: Convenient but weak. These are susceptible to SIM swapping and interception. They should be used only as a last resort.
- Hardware Keys (FIDO/U2F): Physical devices like YubiKeys. They represent the highest tier of “something you have.”
import { generateSecret, verifyToken } from 'node-2fa';
// 1. Generate MFA secret for a user
const newSecret = generateSecret({ name: 'MyApp', account: 'user@example.com' });
// Store newSecret.secret in DB and show newSecret.qr to user
// 2. Verify the 6-digit code during login
const isValid = verifyToken(user.mfaSecret, submittedCode);
if (isValid?.delta === 0) {
// Access granted
}
While TOTP is vastly superior to no MFA, it is still phishable. If a user enters their 6-digit code into a fake site, the attacker can immediately use that code on the real site. This vulnerability is what led to the development of WebAuthn.
c. WebAuthn and Passkeys
WebAuthn (Web Authentication) is a browser API that allows for phishing-resistant, public-key-based authentication. It is the core of “Passkeys.” Instead of a shared secret (password), the user’s device (phone, laptop, or YubiKey) generates a unique public/private key pair for a specific domain. The server only ever stores the public key.
- Registration: The server sends a “challenge.” The device signs the challenge with its private key and sends the signature and public key back.
- Authentication: The server sends a new challenge. The device signs it and sends only the signature.
// Conceptual WebAuthn Registration (Client Side)
const credential = await navigator.credentials.create({
publicKey: {
challenge: Uint8Array.from("server-generated-random-string", c => c.charCodeAt(0)),
rp: { name: "My Secure App", id: "myapp.com" },
user: {
id: Uint8Array.from("user-id-123", c => c.charCodeAt(0)),
name: "alice@example.com",
displayName: "Alice"
},
pubKeyCredParams: [{ alg: -7, type: "public-key" }], // ES256
authenticatorSelection: { residentKey: "required" },
timeout: 60000
}
});
Because the browser verifies the domain (rp.id), a Passkey for bank.com will never work on bank-login-scam.com. This hardware-level binding makes WebAuthn effectively immune to traditional phishing. Passkeys further improve this by allowing these credentials to be synchronized across a user’s devices (via iCloud Keychain or Google Password Manager), solving the “lost device” problem associated with hardware keys.
Complete Example Session
// ============================================
// PART 1: SECURE HASHING SETUP
// ============================================
import argon2 from 'argon2';
const HASH_CONFIG = {
type: argon2.argon2id,
memoryCost: 2 ** 16, // 64MB
timeCost: 3,
parallelism: 4
};
// ============================================
// PART 2: USER REGISTRATION (PASSWORD)
// ============================================
async function registerUser(email, plainPassword) {
const passwordHash = await argon2.hash(plainPassword, HASH_CONFIG);
await db.users.create({ email, passwordHash, mfaEnabled: false });
}
// ============================================
// PART 3: TOTP SETUP (MFA)
// ============================================
import { generateSecret } from 'node-2fa';
async function enableMFA(userId) {
const secret = generateSecret({ name: "SafeApp", account: userId });
await db.users.update(userId, { mfaSecret: secret.secret });
return secret.qr; // Send to frontend
}
// ============================================
// PART 4: LOGIN STEP 1 (PASSWORD VERIFY)
// ============================================
async function loginStep1(email, password) {
const user = await db.users.findByEmail(email);
const valid = await argon2.verify(user.passwordHash, password);
if (!valid) throw new Error("Unauthorized");
return user.mfaEnabled ? "MFA_REQUIRED" : "SUCCESS";
}
// ============================================
// PART 5: LOGIN STEP 2 (TOTP VERIFY)
// ============================================
import { verifyToken } from 'node-2fa';
function loginStep2(userSecret, code) {
const result = verifyToken(userSecret, code);
if (!result || result.delta !== 0) throw new Error("Invalid MFA");
return "SUCCESS";
}
// ============================================
// PART 6: WEBAUTHN CHALLENGE GENERATION
// ============================================
function generateWebAuthnChallenge(userId) {
const challenge = crypto.randomBytes(32);
db.challenges.store(userId, challenge);
return challenge;
}
// ============================================
// PART 7: WEBAUTHN REGISTRATION (SERVER)
// ============================================
import { verifyRegistrationResponse } from '@simplewebauthn/server';
async function completePasskeyReg(userId, response) {
const expectedChallenge = await db.challenges.get(userId);
const verification = await verifyRegistrationResponse({
response,
expectedChallenge,
expectedOrigin: 'https://myapp.com',
expectedRPID: 'myapp.com',
});
if (verification.verified) {
await db.passkeys.save(userId, verification.registrationInfo);
}
}
// ============================================
// PART 8: RATE LIMITING MIDDLEWARE
// ============================================
// Prevent brute force
import rateLimit from 'express-rate-limit';
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5 // 5 failed attempts per IP
});
// ============================================
// PART 9: SESSION REGENERATION
// ============================================
async function finalizeLogin(req, user) {
req.session.regenerate((err) => {
req.session.userId = user.id;
req.session.save();
});
}
// ============================================
// PART 10: AUTOMATIC RE-HASHING
// ============================================
async function handleLegacyHash(user, password) {
if (argon2.needsRehash(user.passwordHash, HASH_CONFIG)) {
const newHash = await argon2.hash(password, HASH_CONFIG);
await db.users.update(user.id, { passwordHash: newHash });
}
}
This sequence covers the full spectrum: secure hashing with Argon2id, MFA setup and verification, WebAuthn integration for Passkeys, and critical defensive measures like rate limiting and session management.
Quick Reference
Hashing Algorithms Comparison
| Algorithm | Type | Security Level | Best For |
|---|---|---|---|
| Argon2id | Memory-Hard | Highest | Modern Applications |
| Bcrypt | Compute-Hard | High | Legacy/Existing apps |
| Scrypt | Memory-Hard | High | General purpose |
| SHA-256 | Fast Hash | Low (Cracking) | Checksums only |
MFA Method Effectiveness
| Method | Phishing Resistant | Security Level | UX Friction |
|---|---|---|---|
| Passkeys | Yes | Highest | Low (Biometric) |
| Hardware Key | Yes | Highest | High (Physical) |
| TOTP (App) | No | Medium | Medium |
| SMS/Email | No | Low | Low |
WebAuthn Key Components
| Component | Role |
|---|---|
| Authenticator | The user device (Phone/Key) that holds the private key |
| Relying Party (RP) | Your server/website requesting authentication |
| Client | The Browser mediating between Authenticator and RP |
| Credential | The public key stored on the server |
Best Practices
✅ Do This:
// Use Argon2id with high memory cost // ✅
const hash = await argon2.hash(pw, { memoryCost: 65536 }); // ✅
// Enforce MFA for administrative accounts // ✅
// Use WebAuthn as the preferred "security" tier // ✅
// Regenerate session IDs after login // ✅
// Set HttpOnly/Secure flags on session cookies // ✅
// Implement account lockout/rate limiting // ✅
❌ Don’t Do This:
// Don't use MD5, SHA-1, or SHA-256 for passwords // ❌
// Don't store plain-text or "pepper" in the database // ❌
// Don't rely on SMS as the only MFA factor // ❌
// Don't allow infinite login attempts // ❌
// Don't log passwords or MFA secrets in plain text // ❌
// Don't use a constant time for hash comparison // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Low Argon2 Settings | Devs use defaults that are too fast | Benchmark for 0.5s – 1s delay |
| Phishable MFA | Reliance on TOTP/SMS | Transition users to Passkeys |
| Session Fixation | Session ID isn’t changed on login | req.session.regenerate() |
| Weak Entropy | Using Math.random() for salts/tokens | Use crypto.randomBytes() |
| No Rate Limiting | Forgetting to protect login routes | Implement express-rate-limit |
| Token Leakage | Sending hashes/secrets to frontend | Never return these in JSON |
Real-World Examples
1. Argon2 Hashing
const hash = await argon2.hash("P@ssword123");
2. TOTP Secret Generation
const secret = twofactor.generateSecret();
3. WebAuthn Origin Check
if (origin !== "https://login.example.com") throw Error();
4. Rate Limit Middleware
app.post('/login', limiter, (req, res) => { ... });
5. Session Cookie Security
session({ cookie: { httpOnly: true, secure: true } });
6. Biometric Auth (WebAuthn)
authenticatorSelection: { userVerification: "preferred" }
7. Argon2 Re-hash Check
if (argon2.needsRehash(hash, newParams)) rehash();
8. Secure Challenge
const challenge = window.crypto.getRandomValues(new Uint8Array(32));
9. Disabling SMS Fallback
user.mfaPreferences = { allowSms: false };
10. Passkey Sync Detection
const isSyncable = result.authenticatorAttachment === 'platform';
Visual
Argon2 Hashing Flow
┌─────────────────────────────────────────────────────────┐
│ PASSWORD INPUT ──────────────────┐ │
│ │ │
│ ┌───────────────────────────────▼───────────────────┐ │
│ │ Argon2id Algorithm │ │
│ ├───────────────────────────────────────────────────┤ │
│ │ 1. Add Random Salt (Unique per user) │ │
│ │ 2. Use Memory Cost (RAM: 64MB+) │ │
│ │ 3. Use Time Cost (Iterations: 3+) │ │
│ │ 4. Parallelize (Threads: 4+) │ │
│ └───────────────────────────────┬───────────────────┘ │
│ │ │
│ RESULTING HASH ◄─────────────────┘ │
│ (Algorithm + Params + Salt + Digest) │
└─────────────────────────────────────────────────────────┘
WebAuthn / Passkey Handshake
┌─────────────┐ ┌───────────────┐ ┌──────────────┐
│ USER DEVICE │ │ BROWSER │ │ SERVER │
└──────┬──────┘ └──────┬────────┘ └──────┬───────┘
│ │ Request Challenge │
│ │◄─────────────────────────┤
│ Invoke Biometrics │ │
│◄───────────────────────┤ │
│ │ │
│ Sign Challenge │ │
├───────────────────────►│ │
│ │ Signed Resp + PubKey │
│ ├─────────────────────────►│
│ │ │ (Store PubKey)
▼ ▼ ▼
Multi-Factor Hierarchy
┌─────────────────────────────────────────────────────────┐
│ SECURITY LEVEL (Low to High) │
│ │
│ [1] Password Only (Dangerous) │
│ [2] Password + SMS (Vulnerable to SIM swap) │
│ [3] Password + TOTP (Vulnerable to Phishing) │
│ [4] PASSKEYS / WEBAUTHN (Phishing Resistant) │
│ │
│ └─► Requirement: Modern Browser + Secure Hardware │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Password Hash | Argon2id (Memory-Hard) |
| Argon2 Memory | 64MB or higher recommended |
| MFA Standard | TOTP (Google/Authy) |
| MFA Gold Standard | WebAuthn / Passkeys |
| Key Logic | Never store shared secrets (WebAuthn) |
| Session Security | Regenerate ID + Secure/HttpOnly |
| Defense Policy | Defense-in-depth / Zero Trust |
Key takeaways:
- Stop using legacy hashes. Algorithms like MD5 and SHA-256 are too fast for password storage; move to Argon2id to resist hardware-accelerated cracking.
- Passwords are inherently weak. No matter how well you hash them, users can be phished. MFA is mandatory for any security-conscious application.
- WebAuthn is the future. By using public-key cryptography and binding credentials to specific domains, WebAuthn (Passkeys) eliminates the possibility of credential theft via phishing.
- Configure Argon2 based on hardware. Set memory and time costs so that verification takes approximately 500ms to 1s on your server to prevent brute-forcing.
- Regenerate sessions. Always issue a new session ID after a successful login to prevent session fixation attacks.
- Phishing resistance is binary. Either your MFA method is phishing-resistant (WebAuthn/Passkeys) or it is not (TOTP/SMS). Guide high-value targets toward resistant methods.
Remember: Authentication security is an arms race against compute power and social engineering. While Argon2id provides the strongest possible protection for the “Something you know” factor, the industry is moving toward a passwordless future where WebAuthn and Passkeys provide cryptographically verifiable proof of identity that cannot be tricked, shared, or stolen in a database breach.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!