FIDO2 and WebAuthn Passwordless Authentication: Implementing Hardware Security Keys in Web Apps

Security tutorial - IT technology blog
Security tutorial - IT technology blog

Context & Why: Moving Beyond Passwords

Passwords are fundamentally broken. According to the Verizon Data Breach Investigations Report, stolen or brute-forced credentials account for over 80% of web application breaches.

Attackers routinely purchase lists of 500 million leaked credentials for under $50 on dark web forums and pump them through automated stuffing bots. After watching an automated botnet slam an SSH port on my own Debian server with 14,000 attempts in a single morning, I stopped relying on shared secrets entirely. Web applications demand that same zero-trust barrier, which is where FIDO2 and WebAuthn come in.

The FIDO2 framework—standardized jointly by the FIDO Alliance and the W3C—splits authentication duties across two protocols:

  • WebAuthn (Web Authentication API): A browser-level JavaScript API exposed on window.navigator.credentials. It allows web applications to request cryptographic credentials directly from local authenticators.
  • CTAP2 (Client to Authenticator Protocol): The transport layer enabling USB, NFC, or Bluetooth security tokens (like a YubiKey 5C or Google Titan) to communicate with your browser and operating system.

Shared secrets never touch the wire. Instead, WebAuthn relies on public-key cryptography. When a user registers, the hardware token generates a fresh, unique keypair scoped strictly to your exact domain name. The private key stays locked inside the physical secure enclave, such as an AAL3-rated secure element. Your backend stores only the public key, the credential ID, and a signature counter.

During login, your server issues a cryptographically random 32-byte challenge. The hardware key signs that payload with its internal private key. The server then validates the resulting signature against the stored public key. Even if an adversary intercepts the full TLS stream or dumps your entire production PostgreSQL database, they obtain nothing they can replay. The stolen public keys cannot log anyone in.

Installation: Setting Up Backend and Client Dependencies

Implementing WebAuthn manually means writing hundreds of lines of ASN.1 parser code and CBOR decoders. Don’t do that. You want an audited, standards-compliant library to parse attestation and assertion payloads.

We will build this service using Python 3.11+, FastAPI, and Duo Labs’ official webauthn package (the reference implementation maintained under the Python Cryptographic Authority ecosystem). If your stack uses Node.js, install @simplewebauthn/server. For Go, pull github.com/go-webauthn/webauthn.

1. Install Backend Dependencies

# Create and activate an isolated virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install FastAPI, ASGI server, and cryptographic dependencies
pip install fastapi uvicorn "webauthn>=2.0.0" pydantic

2. Front-End Client Options

All current desktop and mobile browsers—Chrome 67+, Firefox 60+, Safari 13+, and Edge—support navigator.credentials natively. Pure JavaScript handles this without heavy UI bundles.

The only friction point is binary encoding. WebAuthn exchanges raw binary data via ArrayBuffer, whereas JSON REST APIs transport strings. You must convert these buffers to base64url strings. You can write your own 5-line conversion helpers, or pull in GitHub’s battle-tested 4KB micro-library:

# Optional: 4KB client wrapper for automatic buffer conversion
npm install @github/webauthn-json

Configuration: Implementing Registration and Authentication Flows

Both registration and login follow a strict two-phase handshake: options generation followed by cryptographic assertion verification.

Step 1: Backend Setup and Registration Handshake

Save this as main.py. We define Relying Party parameters, create in-memory registries for our test users, and expose registration endpoints:

import os
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from webauthn import (
    generate_registration_options,
    verify_registration_response,
    generate_authentication_options,
    verify_authentication_response,
    options_to_json,
)
from webauthn.helpers.structs import (
    AttestationConveyancePreference,
    AuthenticatorSelectionCriteria,
    UserVerificationRequirement,
    PublicKeyCredentialDescriptor,
)

app = FastAPI(title="WebAuthn Demo")

# Relying Party (RP) Settings - must match your public origin in production
RP_ID = "localhost"
RP_NAME = "Zero-Trust Auth Portal"
ORIGIN = "http://localhost:8000"

# Simulated datastores (swap for PostgreSQL or Redis in production)
db_users = {}          # username -> user_id (bytes)
db_credentials = {}    # username -> list of registered credentials
pending_challenges = {} # username -> raw base64url challenge string

class UserRequest(BaseModel):
    username: str

@app.post("/api/register/start")
def register_start(data: UserRequest):
    username = data.username.strip().lower()
    user_id = db_users.setdefault(username, os.urandom(16))
    
    options = generate_registration_options(
        rp_id=RP_ID,
        rp_name=RP_NAME,
        user_id=user_id,
        user_name=username,
        attestation=AttestationConveyancePreference.NONE,
        authenticator_selection=AuthenticatorSelectionCriteria(
            user_verification=UserVerificationRequirement.PREFERRED,
            resident_key="preferred",
        ),
    )
    pending_challenges[username] = options.challenge
    return JSONResponse(content=options_to_json(options))

@app.post("/api/register/finish")
async def register_finish(request: Request):
    body = await request.json()
    username = body.get("username", "").strip().lower()
    credential_payload = body.get("credential")
    expected_challenge = pending_challenges.pop(username, None)

    if not expected_challenge:
        raise HTTPException(status_code=400, detail="Challenge timed out or missing")

    try:
        verification = verify_registration_response(
            credential=credential_payload,
            expected_challenge=expected_challenge,
            expected_origin=ORIGIN,
            expected_rp_id=RP_ID,
            require_user_verification=False,
        )
    except Exception as exc:
        raise HTTPException(status_code=400, detail=f"Attestation failed: {str(exc)}")

    db_credentials[username] = {
        "credential_id": verification.credential_id,
        "public_key": verification.credential_public_key,
        "sign_count": verification.sign_count,
    }
    return {"status": "ok", "message": "Hardware key bound successfully"}

Step 2: Authentication Handshake on Backend

Next, append the assertion endpoints to main.py. This challenges registered keys during subsequent logins:

@app.post("/api/login/start")
def login_start(data: UserRequest):
    username = data.username.strip().lower()
    cred = db_credentials.get(username)
    if not cred:
        raise HTTPException(status_code=404, detail="No registered keys for user")

    options = generate_authentication_options(
        rp_id=RP_ID,
        allow_credentials=[PublicKeyCredentialDescriptor(id=cred["credential_id"])],
        user_verification=UserVerificationRequirement.PREFERRED,
    )
    pending_challenges[username] = options.challenge
    return JSONResponse(content=options_to_json(options))

@app.post("/api/login/finish")
async def login_finish(request: Request):
    body = await request.json()
    username = body.get("username", "").strip().lower()
    credential_payload = body.get("credential")
    expected_challenge = pending_challenges.pop(username, None)
    cred = db_credentials.get(username)

    if not expected_challenge or not cred:
        raise HTTPException(status_code=400, detail="Invalid session context")

    try:
        verification = verify_authentication_response(
            credential=credential_payload,
            expected_challenge=expected_challenge,
            expected_origin=ORIGIN,
            expected_rp_id=RP_ID,
            credential_public_key=cred["public_key"],
            credential_current_sign_count=cred["sign_count"],
            require_user_verification=False,
        )
    except Exception as exc:
        raise HTTPException(status_code=401, detail=f"Signature invalid: {str(exc)}")

    # Guard against cloned authenticators
    if verification.new_sign_count <= cred["sign_count"] and cred["sign_count"] > 0:
        raise HTTPException(status_code=403, detail="Cloned authenticator detected!")

    cred["sign_count"] = verification.new_sign_count
    return {"status": "ok", "user": username, "token": "session_active_sample"}

Step 3: Client-Side Browser Implementation

This lightweight JavaScript snippet handles base64url transformations and talks directly to the browser’s credential engine:

// Base64URL to ArrayBuffer decoder
function parseBase64Url(base64UrlStr) {
  let base64 = base64UrlStr.replace(/-/g, '+').replace(/_/g, '/');
  while (base64.length % 4) base64 += '=';
  const raw = atob(base64);
  return Uint8Array.from(raw, c => c.charCodeAt(0)).buffer;
}

// ArrayBuffer to Base64URL encoder
function bufferToBase64Url(buffer) {
  const bytes = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

async function registerKey(username) {
  // 1. Fetch challenge configuration
  const startRes = await fetch('/api/register/start', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username })
  });
  const options = JSON.parse(await startRes.json());

  // Convert string tokens back into binary buffers
  options.challenge = parseBase64Url(options.challenge);
  options.user.id = parseBase64Url(options.user.id);
  if (options.excludeCredentials) {
    options.excludeCredentials.forEach(c => c.id = parseBase64Url(c.id));
  }

  // 2. Activate security key (prompt LED will flash)
  const cred = await navigator.credentials.create({ publicKey: options });

  // 3. Serialize binary assertion back to backend
  const payload = {
    username,
    credential: {
      id: cred.id,
      rawId: bufferToBase64Url(cred.rawId),
      type: cred.type,
      response: {
        attestationObject: bufferToBase64Url(cred.response.attestationObject),
        clientDataJSON: bufferToBase64Url(cred.response.clientDataJSON),
      }
    }
  };

  const finishRes = await fetch('/api/register/finish', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  
  const result = await finishRes.json();
  alert(result.message || 'Key registered!');
}

Verification & Monitoring: Testing and Securing in Production

Fire up your local server:

uvicorn main:app --host 127.0.0.1 --port 8000 --reload

Validating the Authentication Cycle

  1. HTTPS Requirement: Browsers restrict navigator.credentials strictly to secure origins. You can test on http://localhost:8000 or http://127.0.0.1:8000. Production environments will immediately throw a NotAllowedError or SecurityError unless served over valid TLS certificates.
  2. Domain Binding: The RP_ID must be an exact match or valid registrable domain suffix. If your app lives at sub.example.com, set RP_ID = "example.com" or RP_ID = "sub.example.com". Setting RP_ID = "otherdomain.com" immediately halts the handshake in the browser. This single rule makes phishing impossible: fake landing pages at evil-login.com cannot extract signatures valid for example.com.
  3. Hardware Touch Verification: When testing with a YubiKey 5 NFC or Feitian ePass, the gold capacitive ring blinks once navigator.credentials.create() fires. Tapping the token triggers the elliptic curve signature (ES256/Ed25519) and returns the completed payload in roughly 150 milliseconds.

Production Security Hardening

Deploying WebAuthn removes password reset vulnerabilities entirely. However, production operations require three explicit safeguards:

  • Detect Counter Rollbacks (Clone Mitigation): Physical authenticators maintain an internal monotonic counter that increments with every touch. If an incoming assertion presents a counter equal to or lower than the stored value (and both are non-zero), someone has duplicated the seed material. Drop the session immediately, flag the account, and trigger an automated incident alert in your SIEM.
  • Mandate Redundant Authenticators: Physical dongles get dropped in subway grates, and laptops die. Never allow a user to register only a single key. Force them to register at least two independent devices—such as a USB YubiKey backed by Touch ID—or issue 8-to-10 one-time offline backup codes hashed with Argon2id.
  • Structured Audit Logging: Track failed assertions specifically. A sudden surge in origin mismatches or challenge timeouts (TTL should be 60 to 120 seconds maximum) indicates someone is embedding your login flow inside an iframe or executing MITM proxy attacks like Evilginx.
Share: