devHọc Dev

Week 1 - Day 5: MFA, Passkeys, RBAC and ABAC

Week 1 – Day 5

This lesson combines 2 topics: MFA & Passkeys, RBAC, ABAC & Authorization Patterns.

Learning Objectives

  • Understand why a password alone is no longer enough in the 2024 threat landscape
  • How TOTP (RFC 6238) works: Google Authenticator, Authy
  • Why SMS OTP is weak and when it is still acceptable
  • WebAuthn / Passkeys: public-key crypto that replaces passwords and fully resists phishing
  • Recovery codes and backup methods for when a user loses their device
  • Distinguish Authentication (who you are) from Authorization (what you are allowed to do)
  • Understand RBAC: roles and permissions, role hierarchy, real-world examples
  • Understand ABAC: attributes (user, resource, environment) and policy engines
  • Introduction to ReBAC: relationship-based (Google Zanzibar, SpiceDB)
  • Recognize and avoid OWASP A01: Broken Access Control

Part 1: MFA & Passkeys

1. Why passwords are not enough

Threat landscape 2024

ThreatHow it worksPassword defense
PhishingA fake site g00gle.com tricks the user into entering their passwordWeak — users are easily fooled
Credential stuffingUses passwords leaked from other sitesWeak — 60-80% of users reuse passwords
Brute forceTries common passwordsStrong if the password is complex
Database breachPassword hashes leak → cracked offlineDepends on the hashing algo
Keylogger / malwareRecords keystrokesCompletely weak
Shoulder surfingWatching while you typeWeak
Social engineeringTricks the user/support into resetting the passwordDepends on the process

Figures (Microsoft, Verizon DBIR 2024):

  • ~99.9% of account compromises can be blocked by enabling MFA
  • Credential stuffing accounts for 40%+ of breach patterns
  • Phishing is the #1 vector for initial access

Authentication "factors"

┌─────────────────┐┌─────────────────┐┌──────────────────┐│Somethingyou││Somethingyou││Somethingyou││KNOW││HAVE││ARE││││││││-password││-phone(SMS)││-fingerprint││-PIN││-TOTPapp││-face││-securityQ││-hardwarekey││-voice│└─────────────────┘└─────────────────┘└──────────────────┘

Multi-Factor Authentication (MFA) = ≥ 2 factors of different types. Password + PIN = 1 factor (both "know"). Password + phone OTP = 2 factors.

2. TOTP — Time-based One-Time Password

Standard

RFC 6238 — TOTP, based on RFC 4226 — HOTP (counter-based).

TOTP(secret, time) = HOTP(secret, floor(time / 30))

HOTP(K, C) = Truncate(HMAC-SHA1(K, C))
  • secret: random 160-bit (20 bytes), shared between the server and the user's device at enrollment
  • time: Unix timestamp in seconds
  • Time step: 30 seconds (standard)
  • Output: 6 digits

Enrollment flow

┌──────┐┌──────────┐┌────────────┐│User││Server││TOTPApp│└──┬───┘└────┬─────┘└─────┬──────┘││││EnableMFA││├──────────────────────────►│││││││Generate20-byterandom│││secret="JBSWY3DPEHPK3PXP"│││││QRcode:otpauth://totp/│││App:user@email.com?│││secret=JBSWY3DPEHPK3PXP&││issuer=App│││◄──────────────────────────│││││ScanQR(manualentryalternative)│├─────────────────────────────────────────────────────────►││││Storesecret││inkeychain││││Entercurrent6-digitcodetoconfirm││◄─────────────────────────────────────────────────────────┤││││POST/verify-mfa{code}││├──────────────────────────►││││TOTP(secret,now)==code?│││Storesecretinuser'sDB││Success│││◄──────────────────────────││

TOTP URI format (otpauth://)

otpauth://totp/MyApp:alice@example.com
   ?secret=JBSWY3DPEHPK3PXP
   &issuer=MyApp
   &algorithm=SHA1
   &digits=6
   &period=30

The app scans the QR → stores it and generates a code every 30s on its own.

Node.js code with otplib

// npm install otplib qrcode
import { authenticator } from "otplib";
import QRCode from "qrcode";

// 1. Enroll: generate a secret for the user
function setupMFA(user) {
  const secret = authenticator.generateSecret();   // base32, 32 chars
  
  // Store it encrypted in the DB
  const uri = authenticator.keyuri(
    user.email,           // account name
    "MyApp",              // issuer
    secret
  );
  
  return { secret, uri };   // user scans uri → QR code
}

// 2. Render QR
const qrDataUrl = await QRCode.toDataURL(uri);

// 3. Verify code
function verifyMFA(user, userCode) {
  const secret = decrypt(user.mfa_secret);
  
  // window=1 allows ±30s clock skew
  return authenticator.verify({ token: userCode, secret });
}

// 4. Generate code (for testing only, the app does this on the user's side)
const currentCode = authenticator.generate(secret);
console.log(currentCode);   // "523891"

Python with pyotp

# pip install pyotp qrcode
import pyotp
import qrcode

# Enroll
secret = pyotp.random_base32()   # "JBSWY3DPEHPK3PXP..."
uri = pyotp.totp.TOTP(secret).provisioning_uri(
    name="alice@example.com",
    issuer_name="MyApp"
)

# Generate QR
img = qrcode.make(uri)
img.save("qr.png")

# Verify
totp = pyotp.TOTP(secret)
print(totp.now())              # "523891"
print(totp.verify("523891"))   # True if within the 30s window

TOTP pitfalls

  • Clock skew: server and device are out of sync → verification usually accepts ±1 window (±30s)
  • Replay: the same code can be reused within the 30s window → store the last-used code, reject if it matches
  • Secret stored in plaintext: must be encrypted at rest, use KMS
  • QR code leak: if the user screenshots the QR and stores it in the cloud, an attacker who takes over the cloud account gets it → enrollment is not one-shot, it can be regenerated

3. SMS OTP — Why is it weak?

How it works

Server → Twilio/AWS SNS → SMS gateway → carrier → user phone
                ↑                          ↑
        many links in the chain     can be intercepted

Specific threats

1. SIM swap (SIM hijacking)

Attacker calls the victim's telco:
  "Hi, I lost my phone, port number XXX to my new SIM"
  → Social-engineers support → port succeeds
  → Every SMS goes to the attacker's SIM
  → Attacker receives the OTP, resets the password

This has happened to many well-known people (Jack Dorsey, crypto whales losing millions of USD).

2. SS7 protocol attack

  • SS7 is an old protocol connecting carriers worldwide
  • An attacker with SS7 access (bought on the dark web or via a corrupt telco) → can intercept SMS for any number worldwide
  • Demonstrated in practice many times

3. SMS phishing (smishing)

  • "Your bank: send OTP 123456 to support to verify"
  • The user sends the OTP to the attacker

4. Telco insider

  • Telco employees can see SMS content

When is SMS OTP still acceptable?

Use caseSMS OTP OK?Reason
Low-value consumer appOKLow breach cost, easy UX
Bank, crypto exchangeNOHigh-value target, SIM swap is severe
HealthcareNOHIPAA, sensitive data
Internal corporateNOPhishing/social engineering vector
Fallback when the user loses TOTP/passkeyOK with limitsBetter than nothing, add friction (waiting period)

NIST 800-63B (2017) classifies SMS OTP as RESTRICTED: not banned, but its use is discouraged, especially for high assurance. Many apps (Google, Microsoft) let you disable SMS entirely.

MFA methods compared

MethodPhishing-resistantSIM swapUX
SMS OTPNoVulnerableEasy
Email OTPNoOK (if email is secure)Easy
TOTP appNo (still enter a code)SafeMedium (needs an app)
Push notificationNo (push fatigue)SafeEasy
Hardware key (FIDO2)YesSafeMust carry it
Passkey (WebAuthn)YesSafeEasy (built into the OS)

4. WebAuthn / Passkeys

The problem every "code" MFA has

User visits g00gle.com (phishing site):
  1. Enters username + password → attacker captures them
  2. Fake site forwards username/password to the real google.com
  3. Google sends an MFA challenge → user enters the TOTP code
  4. User types the 6 digits into g00gle.com → attacker captures them
  5. Attacker uses the TOTP code within the 30s window → login succeeds

TOTP, SMS and email OTP are all not phishing-resistant because the user "types a code" into whatever site is in front of them.

WebAuthn / FIDO2 principles

Public-key cryptography:
  - At registration: the device generates a keypair (private + public)
  - Server stores the PUBLIC key, bound to the origin (https://example.com)
  - Private key NEVER LEAVES the device

Authentication:
  - Server sends a challenge (random bytes)
  - Device signs the challenge with the PRIVATE key
  - BOUND TO THE ORIGIN — the browser only allows the key on the correct domain
  - Server verifies the signature with the PUBLIC key

Phishing impossible: if the user lands on g00gle.com, the browser will not allow the google.com key → there is nothing to type or leak.

Passkey vs Hardware Security Key

┌──────────────────────────┐┌──────────────────────────┐│Passkey││HardwareSecurityKey││││(YubiKey,Titan)││-Storedonthedevice││-Separatephysicalunit││(iCloudKeychain,││-USB/NFC/Bluetooth││GooglePasswordMgr,││-Nosync││WindowsHello)││-Durable,anti-malware││-Syncedviacloud││-Mustcarryitwithyou││-ExcellentUX││-Premium(enterprise)││-TouchID/FaceID│││└──────────────────────────┘└──────────────────────────┘
PasskeyHardware Key
Phishing-resistantYesYes
Sync across devicesYes (via iCloud/Google)No (needs multiple keys)
Lost device recoveryRestore from the cloudNeeds a backup key
UXExcellentGood, but must be plugged in
CostFree$25-70 per key
Best forConsumerEnterprise, high-value accounts

Registration flow (WebAuthn)

// 1. Server creates a challenge
const challenge = crypto.randomBytes(32);
// Store the challenge bound to the session

// 2. Client browser
const credential = await navigator.credentials.create({
  publicKey: {
    challenge: challenge,
    rp: { name: "MyApp", id: "example.com" },
    user: {
      id: Uint8Array.from(userId, c => c.charCodeAt(0)),
      name: "alice@example.com",
      displayName: "Alice",
    },
    pubKeyCredParams: [
      { alg: -7,  type: "public-key" },   // ES256
      { alg: -257, type: "public-key" },  // RS256
    ],
    authenticatorSelection: {
      authenticatorAttachment: "platform",   // built-in (TouchID, etc.)
      userVerification: "required",
      residentKey: "required",               // discoverable, for passkeys
    },
    attestation: "none",
  },
});

// 3. Send credential.id, credential.publicKey, clientDataJSON to server
// 4. Server verifies, stores publicKey bound to the user

Authentication flow

// 1. Server creates a challenge
// 2. Client
const assertion = await navigator.credentials.get({
  publicKey: {
    challenge: challenge,
    rpId: "example.com",
    userVerification: "required",
  },
});

// 3. Send signature to server
// 4. Server verifies the signature with the stored publicKey
//    Verify rpIdHash, challenge, origin, signature

In practice, use a library such as SimpleWebAuthn:

// npm install @simplewebauthn/server @simplewebauthn/browser
import { generateRegistrationOptions, verifyRegistrationResponse } from "@simplewebauthn/server";

// Server side
const options = await generateRegistrationOptions({
  rpName: "MyApp",
  rpID: "example.com",
  userID: Buffer.from(user.id),
  userName: user.email,
  attestationType: "none",
  authenticatorSelection: {
    residentKey: "required",
    userVerification: "required",
  },
});

// Browser side
import { startRegistration } from "@simplewebauthn/browser";
const attestation = await startRegistration(options);

// Server verify
const verification = await verifyRegistrationResponse({
  response: attestation,
  expectedChallenge: storedChallenge,
  expectedOrigin: "https://example.com",
  expectedRPID: "example.com",
});

if (verification.verified) {
  // Store verification.registrationInfo.credentialPublicKey, credentialID
}

5. Recovery Codes & Backup

A user who loses their phone / hardware key needs recovery, otherwise the account is locked forever.

Recovery codes pattern

When MFA is enabled, the server generates 10 one-time codes:
  4f7a-9b2c
  3d8e-1c5f
  9a2b-7e4d
  ... 7 more codes

The user is asked to:
  - Store them offline (print, password manager)
  - Each code can be used only once
  - Use them to bypass MFA when needed

Implementation:

function generateRecoveryCodes(count = 10) {
  return Array.from({ length: count }, () => {
    const bytes = crypto.randomBytes(4);
    return bytes.toString("hex").slice(0, 8);
  });
}

// Store the HASH of the recovery codes (like a password)
const hashes = await Promise.all(
  codes.map(c => bcrypt.hash(c, 12))
);
// DB.user.recovery_code_hashes = hashes

// Verify
async function verifyRecoveryCode(user, code) {
  for (let i = 0; i < user.recovery_code_hashes.length; i++) {
    const hash = user.recovery_code_hashes[i];
    if (hash && await bcrypt.compare(code, hash)) {
      user.recovery_code_hashes[i] = null;   // invalidate
      await user.save();
      return true;
    }
  }
  return false;
}

Multiple methods

User profile:
  ✓ Password (always)
  ✓ Passkey 1: "iPhone 15"     (primary)
  ✓ Passkey 2: "Macbook Air"   (backup)
  ✓ TOTP: "Google Authenticator"  (backup)
  ✓ Recovery codes: 8/10 remaining
  ✗ SMS (disabled by user)

Best practice: let users enroll multiple passkeys on multiple devices → losing one device still lets them log in.

Questioning the recovery flow

Recovery methodSecure?
Email reset linkOK if the email has MFA
SMS reset linkWeak (SIM swap)
Security questionsVery weak (guessable/Googleable)
Backup codesGood
Identity verification (passport upload)Good but manual
Trusted contactOK for consumer (Apple ID, Google)

Part 2: RBAC, ABAC & Authorization Patterns

1. Authentication vs Authorization

┌─────────────────────────────┐┌─────────────────────────────┐│AUTHENTICATION(AuthN)││AUTHORIZATION(AuthZ)││"Whoareyou?"││"Whatcanyoudo?"││││││-Password││-Roles││-MFA││-Permissions││-OIDC││-Policies││-Session││-Resourceownership││││││Output:useridentity││Output:allow/deny│└─────────────────────────────┘└─────────────────────────────┘Step1Step2(coveredinW2)(today'slesson)

Why does the distinction matter?

Some people assume: "Once logged in, you can access everything" → broken access control (OWASP A01 #1).

A real-world bug:

# User A views their own order
GET /api/orders/12345

# Server only checks "user authenticated?" → YES
# Does not check "does order 12345 belong to user A?"
# → User A changes the ID and views User B's order
GET /api/orders/99999   ← belongs to User B → still returned!

This is IDOR (Insecure Direct Object Reference), an extremely common vulnerability.

2. RBAC — Role-Based Access Control

Basic concept

┌───────┐┌───────┐┌──────────────┐│User│──────►│Role│──────►│Permission│└───────┘has└───────┘grants└──────────────┘│▼┌──────────────────┐│Action+Resource││"read:orders"││"write:users"│└──────────────────┘

A user is assigned a role → the role has permissions → a permission allows an action on a resource type.

Example: blog platform

Roles:├──admin│└──permissions:[│posts:create,posts:read,posts:update,posts:delete,│users:read,users:update,users:delete,│site:configure│]├──editor│└──permissions:[posts:create,posts:read,posts:update]├──viewer│└──permissions:[posts:read]└──anonymous└──permissions:[posts:read]←publicpostsonly

Role hierarchy

Roles can "inherit" permissions:

admin
  ↑ inherits
editor
  ↑ inherits
viewer

admin automatically has every permission of editor, and editor has every permission of viewer. Less duplication.

Database schema

-- Roles
CREATE TABLE roles (
  id       SERIAL PRIMARY KEY,
  name     VARCHAR(50) UNIQUE,
  parent_id INT REFERENCES roles(id)   -- hierarchy
);

-- Permissions
CREATE TABLE permissions (
  id   SERIAL PRIMARY KEY,
  name VARCHAR(100) UNIQUE   -- "posts:create"
);

-- Many-to-many
CREATE TABLE role_permissions (
  role_id       INT REFERENCES roles(id),
  permission_id INT REFERENCES permissions(id),
  PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE user_roles (
  user_id INT REFERENCES users(id),
  role_id INT REFERENCES roles(id),
  PRIMARY KEY (user_id, role_id)
);

Node.js code — middleware

// Get the user's permissions (cached)
async function getUserPermissions(userId) {
  const cached = await cache.get(`perms:${userId}`);
  if (cached) return cached;
  
  // Query roles + hierarchy + permissions
  const perms = await db.query(`
    WITH RECURSIVE role_tree AS (
      SELECT id FROM roles WHERE id IN (
        SELECT role_id FROM user_roles WHERE user_id = $1
      )
      UNION
      SELECT r.parent_id FROM roles r
      JOIN role_tree rt ON r.id = rt.id
      WHERE r.parent_id IS NOT NULL
    )
    SELECT DISTINCT p.name FROM permissions p
    JOIN role_permissions rp ON rp.permission_id = p.id
    WHERE rp.role_id IN (SELECT id FROM role_tree)
  `, [userId]);
  
  const list = perms.rows.map(r => r.name);
  await cache.set(`perms:${userId}`, list, 60);
  return list;
}

// Middleware
function requirePermission(perm) {
  return async (req, res, next) => {
    const perms = await getUserPermissions(req.user.id);
    if (!perms.includes(perm)) {
      return res.status(403).json({ error: "Forbidden" });
    }
    next();
  };
}

// Route
app.delete("/posts/:id",
  requireAuth,
  requirePermission("posts:delete"),
  deletePostHandler
);

RBAC pros / cons

ProsCons
Simple, easy to understand and implementCannot handle "user A may only edit their own posts"
Good for a few clear rolesRole explosion: every combination → a new role
Easy to audit (see what each role can do)No context (time, location, IP)
Widely supported (DB native, frameworks)Static — hard to change in real time

Role explosion example: you have 5 departments × 4 levels × 3 regions = 60 roles → a management nightmare.

3. ABAC — Attribute-Based Access Control

How does it differ from RBAC?

RBAC: User → Role → Permission
ABAC: User attrs + Resource attrs + Environment → Policy → Allow/Deny

Decisions are based on attributes:

Attribute typeExamples
User (Subject)dept, level, clearance, location, age
Resource (Object)owner, classification, type, dept
Actionread, write, delete, share
Environmenttime, IP, device, MFA passed, request method

Example ABAC policy

Policy: "Doctors may only view patient records of their own department
         during business hours from internal machines"

ALLOW
  IF user.role == "doctor"
  AND resource.type == "patient_record"
  AND user.department == resource.department
  AND environment.time BETWEEN 08:00 AND 18:00
  AND environment.ip IN hospital_network

Same user doctor, same action read, same resource type, yet the result differs by context — RBAC cannot do this.

Policy languages

1. XACML (eXtensible Access Control Markup Language)

  • OASIS standard, XML
  • Complex, academic → rarely used in startups

2. AWS IAM Policy (JSON-based ABAC + RBAC hybrid)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/${aws:username}/*",
    "Condition": {
      "IpAddress": { "aws:SourceIp": "10.0.0.0/8" },
      "DateGreaterThan": { "aws:CurrentTime": "2025-01-01T00:00:00Z" }
    }
  }]
}

3. OPA / Rego (Open Policy Agent)

package authz

default allow = false

allow {
    input.user.role == "doctor"
    input.resource.type == "patient_record"
    input.user.department == input.resource.department
    time.now_ns() <= time.parse_rfc3339_ns(input.resource.expires_at)
}

OPA runs as a sidecar/service; the app sends input (user, resource, action) and gets back allow/deny. Popular for Kubernetes admission control and microservices.

4. AWS Cedar (2023)

permit (
    principal in Group::"doctors",
    action == Action::"viewRecord",
    resource
) when {
    principal.department == resource.department &&
    context.time >= time("08:00:00") &&
    context.time <= time("18:00:00")
};

Cedar has a formal verifier (proved correct), is schema-aware, and its syntax is easier than Rego.

ABAC architecture

┌──────────────────┐│Client│└────────┬─────────┘│Request:GET/record/42▼┌──────────────────┐┌──────────────────┐│PolicyEnforce-││PolicyAdmin││mentPoint(PEP)││Point(PAP)││app/proxy││(policyUI)│└────────┬─────────┘└─────────┬────────┘│Query:allow?│define▼▼┌──────────────────────────────────────────┐│PolicyDecisionPoint(PDP)││(OPA,Cedar,AWSIAM)│└────────┬─────────────────────────────────┘│fetchattributes▼┌──────────────────┐│PolicyInfo││Point(PIP)││(DB,LDAP,...)│└──────────────────┘
ComponentRole
PEPIntercepts the request, calls the PDP for a decision
PDPEvaluates the policy, returns allow/deny
PAPWhere admins write policies
PIPProvides attributes (user, resource) to the PDP

RBAC vs ABAC

RBACABAC
Decision based onRoleAttributes (user/resource/env)
Context-aware (time, IP)No (needs extension)Yes
"User may only edit their own posts"Hard (needs per-resource policy)Easy (user.id == resource.owner_id)
ManagementSimple, easy UIComplex, needs a policy language
AuditEasy (list role → permission)Hard (must evaluate policy against real data)
When to useFew, clear roles (CMS, basic SaaS)Complex compliance (healthcare, finance, multi-tenant SaaS)

4. ReBAC — Relationship-Based Access Control

Concept

ReBAC models permissions as graph relationships:

user:alice──member──►group:engineeringgroup:engineering──viewer──►doc:design-spec│└──alicehasviewerpermissiononthedocuser:bob──owner──►doc:design-spec│└──bobistheowner→higherpermission

Google Zanzibar (2019 paper)

Google published a paper describing its unified authorization system serving Drive, Docs, YouTube, Cloud — handling trillions of permission checks/day.

A simple tuple model:

<object>#<relation>@<subject>

doc:readme#viewer@user:alice
doc:readme#viewer@group:engineering#member
group:engineering#member@user:bob

Query:

Can user:alice view doc:readme?
  → Find a path from alice to doc:readme with relation "viewer" or higher
  → Answer in < 10ms with consistency guarantees
SpiceDBOpenFGAPermify
OriginAuthZedAuth0/OktaPermify Inc
Inspired byZanzibarZanzibarZanzibar
Open sourceYesYes (CNCF)Yes
Use caseProduction, enterpriseMainstreamProduction

Example schema (SpiceDB)

definition user {}

definition group {
  relation member: user
}

definition document {
  relation owner: user
  relation viewer: user | group#member
  relation editor: user | group#member
  
  permission view = viewer + editor + owner
  permission edit = editor + owner
  permission delete = owner
}
# Write relationships
zed relationship create document:readme viewer user:alice
zed relationship create group:eng member user:bob
zed relationship create document:readme viewer group:eng#member

# Check
zed permission check document:readme view user:alice    # true
zed permission check document:readme delete user:alice  # false
zed permission check document:readme view user:bob       # true (through group)

When does ReBAC shine?

Use cases that fit ReBAC:
- File sharing (Google Drive, Dropbox, Notion)
- Collaborative docs (figma, Linear, GitHub repos)
- Multi-tenant SaaS (tenant → workspace → project → user)
- Social network (friend-of-friend, group access)
- Healthcare (patient → care team → records)

Common trait: resource ownership and sharing are first-class concepts that cannot be squeezed into a "role".

5. Authorization Pitfalls — OWASP A01

Pitfall 1: Client-side authorization

<!-- ❌ WRONG: Hide the delete button for non-admins -->
<button v-if="user.role === 'admin'" @click="deletePost">Delete</button>

<!-- The API endpoint does not check → attacker calls it directly: -->
<!-- curl -X DELETE /api/posts/123 -H "Authorization: ..." -->

The UI is just UX, not security. Every authorization check must happen on the backend.

Pitfall 2: IDOR (Insecure Direct Object Reference)

// ❌ WRONG
app.get("/orders/:id", requireAuth, async (req, res) => {
  const order = await db.orders.findById(req.params.id);
  return res.json(order);   // no ownership check!
});

// ✅ RIGHT
app.get("/orders/:id", requireAuth, async (req, res) => {
  const order = await db.orders.findById(req.params.id);
  if (!order) return res.status(404).end();
  if (order.user_id !== req.user.id && !req.user.isAdmin) {
    return res.status(403).end();   // or 404 to avoid leaking existence
  }
  return res.json(order);
});

Pitfall 3: Missing function-level authz

// ❌ WRONG: only requires auth, not a role
app.delete("/admin/users/:id", requireAuth, deleteUser);

// ✅ RIGHT
app.delete("/admin/users/:id",
  requireAuth,
  requirePermission("users:delete"),
  deleteUser
);

A path starting with /admin/* is not magically "admin only"; you need explicit middleware.

Pitfall 4: Mass assignment

// ❌ WRONG
app.put("/users/:id", requireAuth, async (req, res) => {
  await db.users.update(req.params.id, req.body);
  // Attacker POST: { name: "...", role: "admin" }
  // → role gets overwritten to admin
});

// ✅ RIGHT: whitelist the fields allowed to be updated
app.put("/users/:id", requireAuth, async (req, res) => {
  const { name, email, phone } = req.body;   // explicit pick
  await db.users.update(req.params.id, { name, email, phone });
});

Pitfall 5: Default permissive

// ❌ WRONG
function canAccess(user, resource) {
  if (user.role === "guest") return false;
  return true;   // default allow!
}

// ✅ RIGHT: default deny
function canAccess(user, resource) {
  if (user.role === "admin") return true;
  if (user.role === "user" && resource.owner_id === user.id) return true;
  return false;   // default deny
}

Pitfall 6: Skipping it in the query

// ❌ WRONG: filtering at the app level → race condition, DB leak via joins
const allOrders = await db.orders.find();
return allOrders.filter(o => o.user_id === req.user.id);

// ✅ RIGHT: filter directly in the query
const myOrders = await db.orders.find({ user_id: req.user.id });

PostgreSQL has Row-Level Security (RLS): it enforces ownership at the DB layer without trusting the app:

CREATE POLICY user_orders ON orders
  FOR SELECT USING (user_id = current_setting('app.user_id')::int);

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

6. Combined models in practice

Large apps usually combine several models:

Layer 1: RBAC for global roles
  - admin, support, billing, user

Layer 2: ABAC for conditions
  - user_dept == resource_dept
  - request_time IN business_hours
  - mfa_passed == true (for sensitive ops)

Layer 3: ReBAC for resource ownership
  - User owns document
  - User member of workspace
  - Workspace shares folder with team

Example of a Notion-like app:

  • Global roles (admin, member, guest) → RBAC
  • Workspace/page/block ownership and sharing → ReBAC
  • Time-based access (token expiry, business hours) → ABAC

Review Questions

  1. Why can password + TOTP still not stop phishing 100%?

    Show answer

    A phishing site can proxy in real time: the user enters their password on g00gle.com, the site forwards it to the real google.com → google.com prompts for MFA → the user enters the TOTP code on g00gle.com → the site forwards the code within the 30s window → login succeeds. A TOTP code is a "temporary shared secret": anyone holding the code can use it. Only WebAuthn/Passkey (which binds the key to the origin) fully resists phishing.

  2. SMS OTP has at least 3 major weaknesses. Name and explain them.

    Show answer

    (1) SIM swap: the attacker social-engineers the telco into porting the number to a new SIM → receives all of the victim's SMS → bypasses MFA. (2) SS7 attack: the protocol between carriers lacks strong authentication → an attacker with SS7 access can intercept SMS for any number worldwide. (3) Smishing: the user is tricked into sending the OTP by phone/SMS to fake support. (4) Bonus: SMS is not end-to-end encrypted, so telco staff and anyone on the transmission path can read it. NIST 800-63B classifies SMS OTP as RESTRICTED: its use is discouraged, especially for high assurance.

  3. What principle does WebAuthn use to resist phishing, and what does "origin binding" mean?

    Show answer

    WebAuthn uses public-key cryptography: the device generates a keypair at registration and the private key never leaves the device. When authenticating, the device signs the challenge with the private key. Origin binding: the browser only allows the key to be used with the exact registered rpId (domain). If the user lands on g00gle.com (phishing), the browser sees the origin does not match → does not allow the google.com key → the user has nothing to "type" or leak → phishing is impossible. Unlike TOTP, where the user types the code into any site.

  4. What is the difference between a Passkey and a hardware security key (YubiKey)?

    Show answer

    A Passkey is stored on the device (iCloud Keychain, Google Password Manager, Windows Hello) and synced via the cloud across the user's devices → lose your phone and you can still log in on your laptop. You authenticate with Touch ID/Face ID. A hardware key is a separate physical device (USB/NFC), not synced, that you must plug in/tap to use. Hardware keys are more durable, resist malware better, and do not depend on a cloud provider: a fit for high-security enterprise. Passkeys offer better UX for consumers and are free. Both are phishing-resistant (both are FIDO2/WebAuthn).

  5. Why should recovery codes be hashed like passwords instead of stored in plaintext?

    Show answer

    Recovery codes are as valuable as a second password: knowing a code = bypassing MFA. If the DB is breached and the codes are in plaintext, the attacker can bypass MFA for every user. Hash them with bcrypt/argon2 like the main password. Note: recovery codes are short (8-12 hex characters, ~32-48 bits of entropy), so they brute force faster than passwords → you still need hashing with a work factor. Some implementations use a denylist approach: store null for used codes instead of deleting the entry, so you can count the remaining codes.

  6. How do Authentication and Authorization differ, and what is the common mistake when only Authentication is done?

    Show answer

    Authentication = "who you are" (verifying identity via password/MFA/OIDC). Authorization = "what you are allowed to do" (checking permission on a specific resource). Common mistake: only checking a requireAuth middleware → every authenticated user can access every resource → IDOR (User A can view User B's order just by changing the ID in the URL). OWASP A01 (Broken Access Control) has been the #1 vulnerability in 2021-2024 precisely because of this mistake.

  7. RBAC has a "role explosion problem". What is it and how does ABAC solve it?

    Show answer

    When an organization has many departments × levels × regions × projects, the number of roles grows multiplicatively (5×4×3×10 = 600 roles). Each user may need several roles, and roles differ only in 1-2 attributes. A management nightmare. ABAC solves this by using attributes instead of hardcoded roles: instead of 600 roles, you have 1 policy user.dept == resource.dept AND user.level >= resource.required_level that works for every combination. Trade-off: ABAC is harder to audit and evaluate.

  8. In which scenarios is an ABAC policy useful where RBAC cannot cope?

    Show answer

    Scenarios that need context: (1) "A user may only edit posts they created": you must check resource.owner_id == user.id, and RBAC has no per-resource ownership concept. (2) "Admin access only during business hours from the company IP": you must check time and IP. (3) "Classified documents only for users with an equivalent or higher clearance level": you must compare attributes. (4) Multi-tenant SaaS: a user of tenant A cannot read tenant B's data: user.tenant_id == resource.tenant_id. RBAC can only do this by creating 1 role per ownership/tenant → role explosion.

  9. What is the core difference between ReBAC and ABAC? Give an example.

    Show answer

    ABAC evaluates attributes (field values) of user/resource/env. ReBAC evaluates graph relationships between entities and traverses paths. Google Drive example: "can alice view doc:X?" — ReBAC traces: alice → member of → team-eng → viewer on → folder:designs → contains → doc:X → answers yes. This is hard to express with simple attributes. ReBAC is natural for collaborative apps (Drive, Notion, GitHub), social networks (friend-of-friend), and multi-level org structures. Google Zanzibar and its open source clones (SpiceDB, OpenFGA) implement this pattern.

  10. Why is filtering authorization at the app level (after the query) a dangerous pattern?

Show answer

(1) Race condition: if permissions change between the query and the filter, data leaks. (2) Dangerous bugs: a dev who forgets the filter leaks data. (3) Performance: the query returns too many records and filtering afterwards is wasteful. (4) Logs/error messages can leak via exceptions. (5) Side channels: the number of records returned can leak existence. The right pattern: filter directly in the query (WHERE user_id = ?) or use Row-Level Security (Postgres RLS) so the DB enforces it and app code cannot bypass it.

Hands-on Exercises

Part 1: MFA & Passkeys

# 1. TOTP with Node.js + otplib
mkdir mfa-lab && cd mfa-lab
npm init -y
npm install otplib qrcode

cat > totp.mjs << 'EOF'
import { authenticator } from "otplib";
import QRCode from "qrcode";

const secret = authenticator.generateSecret();
console.log("Secret:", secret);

const uri = authenticator.keyuri("alice@example.com", "MyApp", secret);
console.log("URI:", uri);

// Print QR ASCII
console.log(await QRCode.toString(uri, { type: "terminal" }));

// Generate current code
console.log("Current code:", authenticator.generate(secret));

// Verify (paste the code from the Google Authenticator app)
import readline from "readline";
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question("Enter code from app: ", (token) => {
  console.log("Valid:", authenticator.verify({ token, secret }));
  rl.close();
});
EOF

node totp.mjs
# - Open Google Authenticator/Authy
# - Scan the QR code in the terminal
# - Enter the 6-digit code, verify

# 2. Passkey demo with SimpleWebAuthn
# Clone https://github.com/MasterKale/SimpleWebAuthn/tree/master/example
# Run the example, register a passkey with TouchID/Face ID

# 3. Look at the passkey in:
# - macOS Keychain (Passwords app)
# - iCloud Keychain settings → Passwords
# - chrome://settings/passwords

# 4. Test phishing resistance:
# - Register a passkey on localhost
# - Try visiting http://127.0.0.1 (a different origin) → the passkey does not work
# - Observe the browser refusing to use the key on the wrong origin

Part 2: RBAC, ABAC & Authorization Patterns

# 1. RBAC from scratch with Node.js + Postgres
mkdir authz-lab && cd authz-lab
docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=pw postgres:16

# Create the schema (see section 2)
# Seed: admin, editor, viewer roles + permissions

# 2. Test IDOR
# - Implement /orders/:id WITHOUT an ownership check
# - Curl with user A's token, call GET /orders/<order_of_userB>
# - Observe the leak
# - Fix the endpoint by adding an ownership check, test again

# 3. OPA (Rego) demo
brew install opa   # or download the binary
cat > policy.rego << 'EOF'
package authz
default allow = false

allow {
    input.user.role == "doctor"
    input.user.department == input.resource.department
}
EOF

cat > input.json << 'EOF'
{
  "user": { "role": "doctor", "department": "cardiology" },
  "resource": { "department": "cardiology" }
}
EOF

opa eval -d policy.rego -i input.json "data.authz.allow"
# → true

# Change resource.department = "neurology" → false

# 4. SpiceDB demo
docker run -p 50051:50051 authzed/spicedb serve --grpc-preshared-key "secret"
# Install the zed CLI, write the schema and relationships (see section 4)

# 5. Postgres Row-Level Security
psql -h localhost -U postgres -d test -c "
  CREATE TABLE notes (id SERIAL, user_id INT, content TEXT);
  ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
  CREATE POLICY user_notes ON notes USING (user_id = current_setting('app.user_id')::int);
"
# SET app.user_id = '1' → only sees user 1's notes

References


Next lesson →