Implementing Phishing-Resistant MFA with FIDO2 & WebAuthn Hardware Keys

Legacy Multi-Factor Authentication (MFA) methods—such as SMS one-time codes, push notifications, and TOTP authenticator apps—are routinely defeated by modern Adversary-in-the-Middle (AiTM) phishing proxies (like Evilginx2). Because a TOTP code is a shared secret typed by the user, a convincing lookalike phishing domain simply relays the victim's password and 6-digit code to the real identity provider in real time.

FIDO2 / WebAuthn (W3C Web Authentication API + CTAP2) eliminates phishing entirely at the cryptographic protocol layer. Instead of sharing a static secret with the server, the authenticator generates an asymmetric public/private key pair scoped strictly to the exact Relying Party ID (rpId), and the browser cryptographically binds the TLS origin into every signed challenge.

MFA Authentication Methods: Security & Phishing Resistance Comparison

Selecting the right authentication factor requires evaluating resistance to AiTM proxies, credential stuffing, and device cloning:

Authentication FactorUnderlying MechanismResistant to AiTM Phishing?Resistant to Server Breach?Hardware Isolation & Clone Detection
SMS / Voice OTPOut-of-band 6-digit code over SS7/cellular carrierNo (SIM swapping & AiTM relay)No (shared state)None
TOTP (RFC 6238)Shared HMAC-SHA1 seed + 30-second time stepNo (real-time proxy relay)No (seed stored on server)Low (QR seeds can be exported/copied)
Push MFA (Approve/Deny)Out-of-band mobile notificationNo (MFA fatigue / prompt bombing)PartialModerate (mobile OS keystore)
FIDO2 / WebAuthn Hardware KeyAsymmetric ECDSA/EdDSA challenge-response bound to origin & rpIdYes (browser enforces exact origin binding)Yes (server only holds public key)High (Secure Element + monotonic signCount)
TEXT
+-----------------------------------------------------------------------------------+
|                  FIDO2 / WEBAUTHN PHISHING-RESISTANT AUTHENTICATION               |
+-----------------------------------------------------------------------------------+
|                                                                                   |
|  1. REGISTRATION CEREMONY (navigator.credentials.create)                          |
|     [Server] -- Generates 32-byte Challenge + rpId ("auth.codecrown.in") -------->|
|     [Browser] -- Verifies TLS Origin Matches rpId, Calls Authenticator via CTAP2->|
|     [YubiKey] -- Generates Key Pair (PrivKey stays in Secure Element)             |
|     [Server] <-- Verifies Attestation & Stores {credential_id, public_key, count} |
|                                                                                   |
|  2. AUTHENTICATION CEREMONY (navigator.credentials.get)                           |
|     [Server] -- Generates Fresh 32-byte Challenge + Allowed Credential IDs ------>|
|     [Browser] -- Builds clientDataJSON {challenge, origin: "https://..."} ------->|
|     [YubiKey] -- User Touches Key -> Signs (rpIdHash || flags || signCount || H)  |
|     [Server] <-- Verifies Signature with Stored Public Key, Origin, & signCount++ |
|                                                                                   |
|  * Why Phishing Fails: If victim visits "https://auth-codecrown.com", the browser |
|    passes the evil origin to the key; signature verification on real server FAILS.|
+-----------------------------------------------------------------------------------+

Core Cryptographic Concepts in WebAuthn

Before implementing the registration and authentication endpoints, understand the four security invariants enforced by the WebAuthn specification:

  1. Relying Party ID (rpId) & Origin Binding: The rpId is a valid domain suffix of the current origin (e.g., codecrown.in for https://auth.codecrown.in). The browser hashes the rpId (SHA-256) and embeds the exact origin URL inside clientDataJSON. Even if a user is tricked into clicking a homograph domain, the authenticator refuses to use keys scoped to the real domain.
  2. Resident vs. Non-Resident Keys (Discoverable Credentials): Server-Side (Non-Resident): The server stores the credential_id and sends it in allowCredentials during login after the user enters their username. Discoverable (Passkeys / Resident): The hardware key stores the user handle internally, enabling passwordless/usernameless authentication flows.
  3. User Presence (UP) vs. User Verification (UV): UP (User Presence): Confirms a human physically touched the capacitive sensor on the security key (defeats remote malware silently signing challenges). UV (User Verification): Confirms local biometric or PIN verification on the authenticator (UserVerificationRequirement.REQUIRED), elevating the login to true multi-factor authentication in a single gesture.
  4. Signature Counter (signCount) Clone Detection: Hardware authenticators increment a monotonic counter on every signature. If the server receives an assertion whose signCount is less than or equal to the previously stored counter, the credential may have been cloned and must be flagged or revoked immediately.

Project Setup & Dependencies

Install Duo's actively maintained webauthn Python library (py_webauthn) alongside FastAPI for clean REST endpoints:

Bash
pip install webauthn==2.7.0 fastapi==0.115.6 uvicorn==0.34.0

Step 1: Backend WebAuthn Relying Party Service (webauthn_service.py)

In production, challenges must be cryptographically random (>= 16 bytes, py_webauthn generates $32\text{ bytes}$ by default), single-use, and stored in an expiring session store (such as Redis with a 60-second TTL) so challenges cannot be replayed.

Python
from dataclasses import dataclass
import os
from typing import Any
from webauthn import (
    generate_authentication_options,
    generate_registration_options,
    options_to_json,
    verify_authentication_response,
    verify_registration_response,
)
from webauthn.helpers import base64url_to_bytes, bytes_to_base64url
from webauthn.helpers.structs import (
    AuthenticatorAttachment,
    AuthenticatorSelectionCriteria,
    PublicKeyCredentialDescriptor,
    ResidentKeyRequirement,
    UserVerificationRequirement,
)


RP_ID = os.getenv("WEBAUTHN_RP_ID", "localhost")
RP_NAME = os.getenv("WEBAUTHN_RP_NAME", "CodeCrown Zero-Trust Portal")
EXPECTED_ORIGIN = os.getenv("WEBAUTHN_ORIGIN", "http://localhost:8000")


@dataclass
class StoredCredential:
    credential_id: bytes
    public_key: bytes
    sign_count: int
    transports: list[str]


# In-memory demonstration stores (replace with PostgreSQL + Redis TTL in production)
USER_CREDENTIALS: dict[str, list[StoredCredential]] = {}
PENDING_CHALLENGES: dict[str, bytes] = {}


def begin_registration(user_id: str, username: str) -> str:
    existing_creds = [
        PublicKeyCredentialDescriptor(id=cred.credential_id)
        for cred in USER_CREDENTIALS.get(user_id, [])
    ]

    options = generate_registration_options(
        rp_id=RP_ID,
        rp_name=RP_NAME,
        user_id=user_id.encode("utf-8"),
        user_name=username,
        user_display_name=username,
        exclude_credentials=existing_creds,
        authenticator_selection=AuthenticatorSelectionCriteria(
            # Restrict to roaming cross-platform hardware keys (e.g., YubiKey) or allow platform passkeys
            authenticator_attachment=AuthenticatorAttachment.CROSS_PLATFORM,
            resident_key=ResidentKeyRequirement.PREFERRED,
            user_verification=UserVerificationRequirement.REQUIRED,
        ),
    )

    # Bind single-use challenge to user session
    PENDING_CHALLENGES[f"reg:{user_id}"] = options.challenge
    return options_to_json(options)


def complete_registration(user_id: str, registration_credential_json: str) -> dict[str, Any]:
    expected_challenge = PENDING_CHALLENGES.pop(f"reg:{user_id}", None)
    if not expected_challenge:
        raise ValueError("Missing or expired registration challenge.")

    verification = verify_registration_response(
        credential=registration_credential_json,
        expected_challenge=expected_challenge,
        expected_origin=EXPECTED_ORIGIN,
        expected_rp_id=RP_ID,
        require_user_verification=True,
    )

    stored = StoredCredential(
        credential_id=verification.credential_id,
        public_key=verification.credential_public_key,
        sign_count=verification.sign_count,
        transports=[],
    )
    USER_CREDENTIALS.setdefault(user_id, []).append(stored)

    return {
        "status": "registered",
        "credential_id": bytes_to_base64url(verification.credential_id),
        "aaguid": str(verification.aaguid),
        "sign_count": verification.sign_count,
    }


def begin_authentication(user_id: str) -> str:
    user_creds = USER_CREDENTIALS.get(user_id, [])
    if not user_creds:
        raise ValueError("No hardware security keys registered for this account.")

    allow_list = [
        PublicKeyCredentialDescriptor(id=cred.credential_id)
        for cred in user_creds
    ]

    options = generate_authentication_options(
        rp_id=RP_ID,
        allow_credentials=allow_list,
        user_verification=UserVerificationRequirement.REQUIRED,
    )

    PENDING_CHALLENGES[f"auth:{user_id}"] = options.challenge
    return options_to_json(options)


def complete_authentication(user_id: str, authentication_credential_json: str, raw_id_b64: str) -> dict[str, Any]:
    expected_challenge = PENDING_CHALLENGES.pop(f"auth:{user_id}", None)
    if not expected_challenge:
        raise ValueError("Missing or expired authentication challenge.")

    target_cred_id = base64url_to_bytes(raw_id_b64)
    matched_cred = next(
        (c for c in USER_CREDENTIALS.get(user_id, []) if c.credential_id == target_cred_id),
        None,
    )
    if not matched_cred:
        raise ValueError("Credential ID not recognized for this user.")

    verification = verify_authentication_response(
        credential=authentication_credential_json,
        expected_challenge=expected_challenge,
        expected_rp_id=RP_ID,
        expected_origin=EXPECTED_ORIGIN,
        credential_public_key=matched_cred.public_key,
        credential_current_sign_count=matched_cred.sign_count,
        require_user_verification=True,
    )

    # Enforce monotonic signature counter check to detect cloned authenticators
    if verification.new_sign_count > 0 and verification.new_sign_count <= matched_cred.sign_count:
        raise SecurityError("Authenticator clone detected: signature counter did not increment!")

    matched_cred.sign_count = verification.new_sign_count
    return {
        "status": "authenticated",
        "user_id": user_id,
        "new_sign_count": verification.new_sign_count,
    }


class SecurityError(Exception):
    pass

Step 2: Frontend Browser WebAuthn Ceremony (webauthn_client.js)

WebAuthn browser APIs (navigator.credentials.create and navigator.credentials.get) operate on binary ArrayBuffer objects, whereas JSON APIs transmit Base64URL strings. Modern browsers provide native PublicKeyCredential.parseCreationOptionsFromJSON() and PublicKeyCredential.parseRequestOptionsFromJSON() helpers to convert server JSON options cleanly:

JavaScript
/**
 * Registers a FIDO2 hardware security key with the Relying Party backend.
 */
async function registerHardwareKey(userId, username) {
  // 1. Fetch challenge & RP options from backend
  const startResp = await fetch("/api/webauthn/register/begin", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ user_id: userId, username }),
  });
  const optionsJson = await startResp.json();

  // 2. Decode Base64URL fields into ArrayBuffers for the browser WebAuthn API
  const publicKeyOptions = PublicKeyCredential.parseCreationOptionsFromJSON(optionsJson);

  // 3. Prompt user to insert/touch FIDO2 hardware key and enter PIN/biometric
  const credential = await navigator.credentials.create({ publicKey: publicKeyOptions });

  // 4. Serialize attestation response and verify on server
  const finishResp = await fetch("/api/webauthn/register/complete", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      user_id: userId,
      credential: credential.toJSON(),
    }),
  });

  if (!finishResp.ok) {
    throw new Error(`Hardware key registration failed: ${await finishResp.text()}`);
  }
  return finishResp.json();
}

/**
 * Authenticates a user using a registered FIDO2 hardware security key.
 */
async function authenticateWithHardwareKey(userId) {
  // 1. Request fresh authentication challenge and allowed credential IDs
  const startResp = await fetch("/api/webauthn/login/begin", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ user_id: userId }),
  });
  const optionsJson = await startResp.json();

  // 2. Parse options and invoke hardware authenticator assertion
  const publicKeyRequestOptions = PublicKeyCredential.parseRequestOptionsFromJSON(optionsJson);
  const assertion = await navigator.credentials.get({ publicKey: publicKeyRequestOptions });
  const assertionJson = assertion.toJSON();

  // 3. Verify cryptographic signature, origin, and signCount on backend
  const finishResp = await fetch("/api/webauthn/login/complete", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      user_id: userId,
      raw_id: assertionJson.id,
      credential: assertionJson,
    }),
  });

  if (!finishResp.ok) {
    throw new Error(`Hardware key authentication failed: ${await finishResp.text()}`);
  }
  return finishResp.json();
}

Production Rollout & Recovery Best Practices

Deploying hardware-backed FIDO2 MFA across an engineering organization requires careful operational planning to prevent lockouts when a user loses or damages their physical key:

  1. Enforce Dual-Key Registration: Require every privileged user (IAM admins, production SSH/bastion operators, finance approvers) to register at least two independent FIDO2 hardware keys (e.g., a primary USB-C nano key kept on their laptop and a backup key stored in a secure physical location) before disabling legacy TOTP/SMS fallback.
  2. Bind rpId to Your Apex Domain (example.com): Setting rpId to your apex domain rather than a single subdomain (login.example.com) allows the same registered hardware keys to authenticate users across app.example.com, vpn.example.com, and admin.example.com without forcing separate registrations per subdomain.
  3. Combine UserVerificationRequirement.REQUIRED with Short Session Lifetimes: Enforcing PIN or biometric verification (UV=true) guarantees that a stolen physical YubiKey found on a desk cannot be used without knowing the owner's PIN.
  4. Automate Enterprise Attestation Filtering (Optional): For high-assurance corporate environments, inspect the authenticator's AAGUID (Authenticator Attestation Globally Unique Identifier) during registration to restrict enrollment exclusively to FIPS 140-3 Level 2/3 validated hardware security keys.

Common Mistakes

  • Leaving legacy SMS or TOTP enabled alongside FIDO2 without Conditional Access policies: If an account supports both a YubiKey and an SMS backup code, an AiTM phishing kit will simply prompt the user to click "Try another way" and downgrade the authentication ceremony to phishable TOTP/SMS.
  • Failing to delete the challenge immediately upon verification: Challenges must be strictly single-use (PENDING_CHALLENGES.pop(...)) and expire within 60–120 seconds. Reusing challenges allows replay attacks within the session window.
  • Deploying WebAuthn over non-HTTPS origins: Outside of http://localhost for local development, browsers strictly refuse to expose navigator.credentials on plaintext HTTP or origins with invalid TLS certificates.

Summary

Implementing FIDO2 / WebAuthn hardware security keys upgrades authentication from phishable shared secrets to origin-bound asymmetric cryptography. By generating single-use server challenges, enforcing UserVerificationRequirement.REQUIRED, verifying rpId and TLS origin bindings, and tracking monotonic signCount increments against cloning, organizations eliminate credential phishing and AiTM session hijacking.