Passkeys and WebAuthn for Developers: How Passwordless Login Works and What to Build

How passkeys work, what your server must verify, and a phased plan for adding them to an app, using the WebAuthn Level 3 standard.

Ankit Singh
Software Engineer
8 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

Passkeys and WebAuthn for Developers: How Passwordless Login Works and What to Build

Passwords fail in a predictable way: people type them into the wrong site. Training doesn't fix that, because a good fake looks identical to the real thing.

Passkeys change what the user proves. Instead of a secret they type, their device proves it holds a private key, and it will only do that for the real site. There's nothing to phish, and nothing worth stealing from your database.

This is the third post in an auth series, after password storage and JWT versus sessions. It covers how passkeys work, the code to add them, what your server must verify, and how to roll them out without locking anyone out.

Sources: the W3C and FIDO Alliance announcements on WebAuthn Level 3, Chrome's developer guidance on passkeys, and NIST SP 800-63B-4. The server code was tested against a software authenticator, since there's no real browser or device in a test suite. Test on real devices before you ship.


What a passkey is

Term

Meaning

WebAuthn

The browser API (navigator.credentials) and W3C standard. Level 3 became a W3C Recommendation on 25 August 2026

Passkey

A discoverable WebAuthn credential: the user picks it from a list and doesn't type a username. Usually synced across their devices by a passkey provider

Relying party (RP)

You: your site or app

RP ID

Your domain, such as example.com. Every credential is locked to it

User handle

A random ID for the account, never an email address

Signing in is a short exchange:

sequenceDiagram
    participant U as User
    participant B as Browser + passkey provider
    participant S as Your server
    S->>B: challenge and RP ID (example.com)
    B->>B: does this page's origin match the RP ID?
    B->>U: Use your passkey for example.com?
    U->>B: Fingerprint, face or PIN
    B->>S: signature over challenge, origin and flags
    S->>S: verify signature, origin, RP ID hash and flags
    S->>B: start a session

Registration has the same shape. The server sends a challenge, the browser creates a new key pair, and it sends back the public key for you to store. The private key never leaves the user's passkey provider.


Why passkeys resist phishing

  • The browser enforces the scope. A page can only use an RP ID that is its own domain or a parent of it. A lookalike site is never offered your users' passkeys.

  • The origin is inside the signed data. The signature covers a client-data blob that records the page's origin, and your server checks it.

  • Nothing secret sits on your server. A database leak exposes public keys, which are useless to an attacker.

  • There's nothing to type, so nothing to hand over.

NIST agrees this matters. SP 800-63B-4 says passwords aren't phishing-resistant, and that an application assessed at AAL2 must offer a phishing-resistant option.

Synced or device-bound?

Authenticator data carries two flags: backup eligible (BE) says the credential may be synced, and backup state (BS) says it currently is. BE never changes for a credential, so your server should store it and reject a change.

NIST allows syncable passkeys at AAL2 with extra requirements. It doesn't allow them at AAL3, which requires a non-exportable key, because syncing makes the key exportable. If you need AAL3, require device-bound credentials.

Synced passkeys also often report a signature counter of zero forever. Only treat the counter as a clone signal when it's nonzero.


What to build

Four endpoints do the job. Two for registration (/passkeys/register/options and /verify) and two for login (/passkeys/login/options and /verify). Each options call creates a random challenge and ties it to the session or the user. Each verify call consumes it.

Registration options

def registration_options(self, user_handle, name):  # user_handle: random bytes, never an email address
        return {
            "challenge": self._new_challenge("create", user_handle),
            "rp": {"id": self.rp_id, "name": self.rp_id},
            "user": {"id": b64u(user_handle), "name": name, "displayName": name},
            "pubKeyCredParams": [{"type": "public-key", "alg": -7}],  # ES256: all this demo verifies
            "excludeCredentials": [{"type": "public-key", "id": cid}
                                   for cid, c in self.credentials.items() if c["user"] == user_handle],
            "authenticatorSelection": {"residentKey": "required", "requireResidentKey": True,
                                       "userVerification": "required" if self.require_uv else "preferred"},
            "attestation": "none",
        }

Each setting is deliberate:

  • residentKey: "required" creates a true passkey, so users can sign in without typing a username.

  • userVerification: "preferred" is Chrome's recommendation. If you choose preferred, your server must not require the verification flag, or devices without a screen lock fail.

  • excludeCredentials stops the same device registering twice.

  • attestation: "none" because you rarely need to know the device model.

  • pubKeyCredParams should list ES256 (-7) and RS256 (-257) in a real deployment. This demo verifies ES256 only, so it only asks for that.

  • The user ID is random bytes. The spec says it must not contain personal information, and it's capped at 64 bytes.

The browser side

The Level 3 JSON helpers turn your server's JSON into the binary options the API wants, and toJSON() turns the result back. You no longer write base64url conversion by hand:

export async function registerPasskey() {
  const options = await (await fetch("/passkeys/register/options", { method: "POST" })).json();
  let credential;
  try {
    credential = await navigator.credentials.create({
      publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options),
    });
  } catch (err) {
    if (err.name === "InvalidStateError") return "This device already has a passkey for your account.";
    if (err.name === "NotAllowedError") return "Cancelled or timed out.";
    throw err;
  }
  const response = await fetch("/passkeys/register/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(credential.toJSON()),
  });
  return response.ok ? "Passkey saved." : "The server rejected the passkey.";
}

export async function signInWithPasskey({ conditional = false } = {}) {
  const options = await (await fetch("/passkeys/login/options", { method: "POST" })).json();
  const credential = await navigator.credentials.get({
    publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
    mediation: conditional ? "conditional" : "optional",
  });
  const response = await fetch("/passkeys/login/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(credential.toJSON()),
  });
  if (response.ok) location.assign("/");
}

// On the login page: offer saved passkeys in the username field's autofill menu
if (await PublicKeyCredential.isConditionalMediationAvailable?.()) {
  signInWithPasskey({ conditional: true }).catch(() => {});
}

For autofill, add the webauthn token to the username field. Saved passkeys then appear in the browser's autofill menu:

<input name="username" autocomplete="username webauthn" autofocus>

Check browser support before relying on the JSON helpers. Libraries such as SimpleWebAuthn's browser package fill the gaps. InvalidStateError means the device already has a passkey, NotAllowedError means the user cancelled or it timed out, and SecurityError usually means an RP ID or HTTPS problem.

What your server must verify

When a login comes back, check all of this, in this order:

  1. The challenge is one you issued, for this session, unused and unexpired.

  2. The type is webauthn.get, the origin is on your allowlist, and crossOrigin isn't true.

  3. The credential exists, and the userHandle matches its owner.

  4. The RP ID hash is the SHA-256 of your RP ID.

  5. The user-presence flag is set, and the user-verification flag too if you require it.

  6. Backup eligibility hasn't changed.

  7. The signature is valid over the authenticator data plus the SHA-256 of the client data.

  8. If either counter is nonzero, the new one must be higher. The spec treats a counter that doesn't increase as a sign of cloning and leaves the response to you.

The first two checks live in one helper, and the rest in the login method. Both are methods of the RelyingParty class:

def _client_data(self, encoded, kind, binding):
        raw = unb64u(encoded)
        try:
            data = json.loads(raw)
        except ValueError:
            raise Rejected("clientDataJSON is not JSON")
        if not isinstance(data, dict) or data.get("type") != f"webauthn.{kind}":
            raise Rejected("wrong ceremony type")
        challenge = data.get("challenge")
        entry = self.pending.pop(challenge, None) if isinstance(challenge, str) else None  # single use
        if entry is None or entry[0] != kind or entry[1] != binding or entry[2] < self.now():
            raise Rejected("unknown, reused, expired or misbound challenge")
        if data.get("origin") not in self.origins:
            raise Rejected("origin not allowed")
        if data.get("crossOrigin"):
            raise Rejected("cross-origin ceremony")
        return raw

    def finish_authentication(self, session_id, cred):
        try:
            record = self.credentials.get(cred["id"])
            response = cred["response"]
            raw = self._client_data(response["clientDataJSON"], "get", session_id)
            auth, signature = unb64u(response["authenticatorData"]), unb64u(response["signature"])
            if response["userHandle"] is None:
                raise Rejected("userHandle missing: discoverable credentials return one")
            user_handle = unb64u(response["userHandle"])
        except (KeyError, TypeError):
            raise Rejected("malformed authentication response")
        if record is None:
            raise Rejected("unknown credential")
        if user_handle != record["user"]:
            raise Rejected("userHandle does not match the credential's owner")
        info = parse_auth_data(auth, attested=False)
        self._check_flags(info)
        if bool(info["flags"] & 0x08) != record["backup_eligible"]:
            raise Rejected("backup eligibility changed, which should never happen")
        try:
            record["key"].verify(signature, auth + hashlib.sha256(raw).digest(), ec.ECDSA(hashes.SHA256()))
        except (InvalidSignature, ValueError):
            raise Rejected("bad signature")
        if (info["count"] or record["count"]) and info["count"] <= record["count"]:
            raise Rejected("signature counter did not increase: the credential may be cloned")
        record["count"], record["backed_up"] = info["count"], bool(info["flags"] & 0x10)
        return record["user"]

Registration verifies the same things plus a few of its own: it decodes the attestation object, checks the public key is valid, confirms the credential ID matches, and refuses an ID that's already registered.

Heads up: don't hand-write this in production. Use a maintained library, such as SimpleWebAuthn for JavaScript, py_webauthn for Python or go-webauthn for Go. The code here shows what a library does for you. The full module, about 220 lines with a small CBOR reader, and its tests are in passkey_rp.py.

Does it hold up?

The tests drive the verifier with a software authenticator that builds correctly signed messages, then forge or corrupt them. Here's a selection of the 19 login attacks, with the reason each one was rejected:

login attempt                                           result
phished at evil.example                                 rejected: origin not allowed
right origin, other RP ID hash                          rejected: rpIdHash does not match this site
origin edited in after signing at evil.example          rejected: bad signature
signed with the attacker's own key                      rejected: bad signature
flags edited after signing (UV set)                     rejected: bad signature
captured assertion replayed                             rejected: unknown, reused, expired or misbound challenge
Alice's credential, Bob's userHandle                    rejected: userHandle does not match the credential's owner
cross-origin iframe                                     rejected: cross-origin ceremony
credential the server never saw                         rejected: unknown credential

The same suite rejects 20 forged registrations, and the CBOR reader agrees with 25 examples from the CBOR RFC's own test appendix. 400 randomly corrupted logins were tried, and none was accepted. Malformed input only ever raised the verifier's own error and never crashed it.

Heads up: returning a different message for each failure helps an attacker probe you. In production, answer with one generic error and keep the specific reason in your logs.

What to store

Field

Why

Credential ID

The lookup key. Unique across all accounts

Public key

Verifies signatures. Never the private key, which you never see

User handle

Ties the credential to its account

Backup eligible, backup state

For policy and risk decisions

Signature counter

Clone signal, when nonzero

Transports

Hints for the browser prompt

Created, last used, a name

So users can manage their passkeys

After login: start a session

A passkey login proves who the user is once. Then issue an ordinary server-side session cookie, as in the previous post. You don't ask for a signature on every request.


Rolling it out

  1. Offer a passkey after a normal login. Chrome's guidance suggests prompting right after a password sign-in, asking for a platform authenticator, so the user can try it with no risk.

  2. Turn on autofill at the login page with the conditional UI shown above.

  3. Let users manage passkeys. Support several per account, with names, last-used dates and a delete button. Level 3 adds signal methods that tell the passkey provider when a credential was removed or a username changed. Chrome and Edge 132 and Safari 26 support them and Firefox doesn't, so feature-detect, and note that the provider decides what to do with the signal.

  4. Make recovery as strong as login. If anyone who controls an email inbox can bypass the passkey, attackers will skip it. For high-value accounts, recovery needs checks of its own.

  5. Measure, then thin out passwords for users who have passkeys. Keep a fallback until you trust the numbers.


Pitfalls

  • The RP ID is effectively permanent. Passkeys are locked to it, so moving domains strands them. Level 3 adds related origin requests, which let one passkey work across several of your domains. The spec requires browsers to support at least five.

  • Don't trust a counter of zero or its absence as proof of anything. Synced passkeys often keep it at zero.

  • Check crossOrigin. A ceremony can run inside a cross-origin iframe, and the client data records that, so an origin check alone isn't enough.

  • It's base64url, not base64. The test suite rejects any non-canonical encoding.

  • Challenges must be random, single-use and short-lived. Otherwise a captured response can be replayed, which the table above shows is rejected.

  • localhost works for development. Everywhere else you need HTTPS.


Checklist

  • Use a maintained WebAuthn library.

  • Request resident keys, attestation: "none", and an exclusion list.

  • Verify challenge, origin, crossOrigin, RP ID hash, flags and signature, in that order.

  • Store the credential ID, public key, user handle, flags and counter.

  • Start a normal session after login.

  • Support multiple passkeys, and make recovery as strong as login.

  • Roll out in stages: offer after login, then autofill, then management, then fewer passwords.

Comments0

Log in to join the discussion.

No comments yet.

Ankit Singh
Ankit Singh

Software Engineer

Read articles by this author.

Subscribe to Ankit Singh's newsletter

Get the articles this author chooses to send by email.