Web & Development

Passkeys and WebAuthn in 2026: A Practical Implementation Guide for Web Developers

Passkeys and WebAuthn in 2026: A Practical Implementation Guide for Web Developers

Passkeys promise passwordless sign-in without storing password secrets, but implementing WebAuthn correctly requires more than calling a browser API. Learn how registration, authentication, server-side verification, discoverable credentials and account recovery fit together in a secure web application.

Passwords have been the default authentication mechanism for web applications for decades. They are also a persistent source of security problems.

Users reuse them. Attackers steal them through phishing. Servers must protect password hashes, manage resets and defend against credential-stuffing attacks.

Passkeys offer a fundamentally different approach.

Instead of asking users to remember a shared secret, passkeys use public-key cryptography and an authenticator controlled by the user. The browser provides a standard interface through WebAuthn, while the server verifies cryptographic evidence that the correct credential was used.

The technology is no longer experimental. WebAuthn is widely available in modern browsers, and its JSON convenience methods have simplified integration considerably.

But building a secure passkey login still requires careful backend design.

This guide explains the architecture, demonstrates the browser-side flows and identifies the server-side checks that developers must not overlook.

1. What exactly is a passkey?

A passkey is a discoverable FIDO credential used to authenticate a user through public-key cryptography.

During registration, an authenticator creates a cryptographic key pair.

The private key remains protected by the authenticator or its credential-management ecosystem. The website receives the corresponding public key and associates it with the user's account.

During authentication, the server issues a fresh challenge. The authenticator signs data associated with that challenge, and the server verifies the signature using the stored public key.

There is no reusable password sent to the website.

An authenticator might be a smartphone, a computer using Windows Hello, a hardware security key or a credential manager supporting synchronized passkeys.

Not every passkey is synchronized across devices. Some credentials remain device-bound, while others can be securely backed up and made available through a credential provider.

The FIDO specifications are designed to resist phishing by binding credentials to the relying party's domain. Biometric data, when used, is handled locally by the device rather than being sent to the website.

2. WebAuthn is the browser API behind passkeys

WebAuthn is the web platform API that enables websites to create and use public-key credentials.

Two browser methods form the foundation:

navigator.credentials.create()
navigator.credentials.get()

The first creates a credential. The second requests authentication using an existing credential.

Both methods work with the publicKey option and require a secure context, normally HTTPS.

Importantly, the browser does not decide whether the user is authenticated. It returns data that the backend must verify.

A successful browser prompt is not proof that a login should be accepted.

The server remains responsible for verifying the challenge, origin, relying-party identifier and cryptographic evidence.

3. Understand the complete architecture

A typical implementation contains four components:

  • The web application frontend, which invokes WebAuthn.
  • The application backend, which generates challenges and verifies responses.
  • The authenticator or passkey provider, which protects the private key.
  • The database, which stores credential metadata and public keys.

The registration flow is: the web application requests registration options; the backend generates a challenge and user data; the browser and authenticator create a credential and key pair; and the backend verifies the result and stores the public key.

The server must never trust registration data merely because it was returned by the browser.

A malicious client can submit arbitrary HTTP requests without using the expected frontend at all.

That is why verification belongs on the server.

4. Generate registration options on the server

Before calling WebAuthn, the backend generates a registration challenge and options.

A representative options object looks like this:

{
  "rp": {
    "name": "Example Application",
    "id": "example.com"
  },
  "user": {
    "id": "dXNlci0xMjM",
    "name": "alex@example.com",
    "displayName": "Alex"
  },
  "challenge": "SERVER_GENERATED_BASE64URL_CHALLENGE",
  "pubKeyCredParams": [
    {
      "type": "public-key",
      "alg": -7
    }
  ],
  "authenticatorSelection": {
    "residentKey": "required",
    "userVerification": "required"
  },
  "attestation": "none",
  "timeout": 300000
}

This is illustrative JSON, not a complete production response.

Several fields matter.

rp.id identifies the relying party. For example, example.com can be used for appropriate subdomains of that domain, subject to WebAuthn's RP ID validation rules.

user.id should be a stable, opaque account identifier encoded as base64url for JSON transport. It should not expose unnecessary personal information.

challenge must be generated using a cryptographically secure random source on the server.

residentKey: "required" requests a discoverable credential, which is necessary for the passkey experience.

userVerification: "required" requests local user verification, such as a device PIN or biometric authentication. The backend must later check that verification actually occurred.

Google's server-side registration guide describes these fields and recommends using a maintained WebAuthn library for generating and validating registration data.

5. Create the passkey in JavaScript

Modern browsers provide a useful method:

PublicKeyCredential.parseCreationOptionsFromJSON()

It converts a JSON representation containing base64url-encoded binary fields into the structure expected by WebAuthn.

This avoids writing custom base64url-to-ArrayBuffer conversion logic for every field.

Here is a simplified browser-side registration function:

async function registerPasskey() {
    const optionsResponse = await fetch(
        '/api/passkeys/register/options',
        {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken
            }
        }
    );

    if (!optionsResponse.ok) {
        throw new Error('Unable to start registration');
    }

    const optionsJson = await optionsResponse.json();

    const publicKey =
        PublicKeyCredential.parseCreationOptionsFromJSON(
            optionsJson
        );

    const credential = await navigator.credentials.create({
        publicKey
    });

    if (!credential) {
        throw new Error('No credential was created');
    }

    const verifyResponse = await fetch(
        '/api/passkeys/register/verify',
        {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken
            },
            body: JSON.stringify(credential.toJSON())
        }
    );

    if (!verifyResponse.ok) {
        throw new Error('Registration verification failed');
    }

    return await verifyResponse.json();
}

The csrfToken variable represents an application-provided anti-CSRF token. The server must validate it. The example also assumes that the page is already associated with a securely authenticated user.

credential.toJSON() provides a JSON-friendly representation of the returned credential, avoiding another layer of manual binary serialization.

These conveniences are available in current browsers, although applications supporting older browser versions should provide compatibility handling.

The code above is only the browser side. It is not a complete authentication implementation.

6. What the server must verify during registration

When the browser returns the new credential, the backend must validate it before storing anything.

At minimum, the verification process must establish that:

  1. The returned challenge matches the one generated for this registration attempt.
  2. The challenge is fresh and has not already been consumed.
  3. The reported origin matches an explicitly trusted application origin.
  4. The authenticator data corresponds to the expected RP ID.
  5. The required user-presence and user-verification conditions are satisfied.
  6. The credential's public key and identifier can be extracted and validated.
  7. The registration is associated with the correct authenticated account.

Depending on the application's policy, additional checks may include supported algorithms, credential uniqueness and attestation requirements.

A successful registration typically stores:

Field Purpose
credential_id Identifies the credential
user_id Links it to an account
public_key Verifies future signatures
sign_count Tracks authenticator counter data
transports Optional authenticator transport hints
created_at Registration timestamp
last_used_at Account management and auditing
backup_eligible / backup_state Optional backup-related metadata

The exact database representation depends on the verification library and application.

Do not implement CBOR parsing, attestation verification or cryptographic signature validation from scratch unless you have a compelling reason and the expertise to maintain it.

The W3C specification defines detailed registration and authentication verification procedures.

7. Authenticate an existing user

Authentication follows a similar structure but does not create a new key pair.

The server generates a new challenge and sends authentication options to the browser.

For a discoverable passkey login, those options might contain:

{
  "challenge": "NEW_SERVER_GENERATED_CHALLENGE",
  "rpId": "example.com",
  "userVerification": "required",
  "timeout": 300000
}

The browser can then request a credential:

async function authenticateWithPasskey() {
    const optionsResponse = await fetch(
        '/api/passkeys/login/options',
        {
            credentials: 'same-origin'
        }
    );

    if (!optionsResponse.ok) {
        throw new Error('Unable to start authentication');
    }

    const optionsJson = await optionsResponse.json();

    const publicKey =
        PublicKeyCredential.parseRequestOptionsFromJSON(
            optionsJson
        );

    const credential = await navigator.credentials.get({
        publicKey
    });

    if (!credential) {
        throw new Error('Authentication was cancelled');
    }

    const verifyResponse = await fetch(
        '/api/passkeys/login/verify',
        {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(credential.toJSON())
        }
    );

    if (!verifyResponse.ok) {
        throw new Error('Authentication failed');
    }

    return await verifyResponse.json();
}

This example assumes the backend associates the issued challenge with a short-lived, anonymous login transaction, applies appropriate rate limiting and establishes a new authenticated session only after successful verification.

The server must look up the credential ID, verify the signed assertion with the stored public key, confirm the challenge and origin, and enforce its user-verification policy.

Only then should it establish the user's session.

parseRequestOptionsFromJSON() is part of the modern WebAuthn API and removes the need to manually decode binary fields in common browser-side integrations.

8. Add passkeys to existing login forms with conditional mediation

One of the most useful WebAuthn features is conditional mediation, sometimes called passkey autofill.

Instead of showing a separate passkey dialog immediately, the browser can offer an available passkey alongside other saved credentials when the user interacts with a login field.

The HTML input can use:

<input
    type="text"
    name="username"
    autocomplete="username webauthn"
>

The application can check for support:

const supported =
    await PublicKeyCredential.isConditionalMediationAvailable();

if (supported) {
    // Request authentication with mediation: 'conditional'.
}

When calling navigator.credentials.get(), the application uses:

{
    publicKey,
    mediation: 'conditional'
}

For discoverable-credential autofill, the server's options should not restrict the request to a specific list of credential IDs.

Conditional mediation is especially useful during a gradual migration from passwords because users do not need to remember whether a particular account has a passkey.

The browser can present appropriate options in the familiar login experience.

9. Why the challenge and origin checks are essential

Passkeys are phishing-resistant, but that does not mean an application can ignore its authentication protocol.

The challenge protects against replay attacks.

Without a fresh, unpredictable challenge, an attacker might attempt to reuse authentication data from a previous session.

The origin and RP ID checks ensure that credentials are being used in the intended website context.

For example, a passkey created for example.com cannot simply be reused by a lookalike phishing site such as examp1e.com.

The browser and authenticator enforce important parts of this domain binding, while the backend independently validates the resulting evidence.

A good implementation uses short-lived challenges, consumes each challenge once and never accepts arbitrary origins merely because they share a familiar-looking hostname.

MDN recommends generating challenges in a trusted environment and invalidating them after a short period, generally no more than about ten minutes.

10. Do not misunderstand signature counters

WebAuthn authenticators can include a signature counter.

Historically, counters helped detect potentially cloned authenticators. If a counter unexpectedly stops increasing, the relying party may consider that a risk signal.

However, not every authenticator maintains a meaningful counter.

Some credentials always report zero. Synchronized credentials can also complicate counter interpretation because multiple devices may use copies of the same credential.

The W3C specification explicitly treats unexpected counter behavior as a possible signal, not definitive proof of cloning.

Therefore, developers should not blindly reject every login whose counter is zero or unchanged.

Use the counter according to the authenticator behavior, the WebAuthn verification library's guidance and the application's security policy.

11. Account recovery is part of passkey security

A passkey implementation is incomplete without a recovery strategy.

What happens when a user loses a device?

What if they delete their only passkey?

What if they change credential providers or cannot access a synchronized credential?

A sensible design allows users to register multiple passkeys and manage them from their account settings.

The management interface should display recognizable credential names, creation dates and recent usage information where available.

Users should be able to revoke credentials they no longer trust.

But the recovery mechanism deserves particular care.

If an attacker can bypass passkey authentication using a weak email recovery process, the overall account is only as secure as that recovery path.

For higher-risk accounts, consider stronger recovery verification, recovery codes, additional registered authenticators and notifications about sensitive account changes.

Google's passkey UX guidance recommends establishing a recovery method and supporting multiple passkeys where appropriate.

12. Common implementation mistakes

Several mistakes repeatedly undermine otherwise promising passkey integrations.

Treating browser success as server authentication. A resolved navigator.credentials.get() promise does not replace server-side cryptographic verification.

Generating challenges in JavaScript. Challenges should come from a trusted server and be bound to the appropriate authentication transaction.

Using the wrong RP ID. Domain scoping is a security feature, not a cosmetic setting. Production, staging and local development environments require deliberate configuration.

Assuming all passkeys synchronize. Device-bound credentials remain an important part of the ecosystem.

Forgetting credential revocation. Users need a way to remove a lost or compromised authenticator from their account.

Creating a weak fallback. A phishing-resistant login loses much of its value if account recovery can be exploited easily.

Ignoring old browsers. Modern JSON convenience methods reduce complexity, but applications with older browser requirements may still need compatibility code.

Skipping CSRF and session protection. Registration and credential-management operations are sensitive account changes. They need the same protections as other high-impact account actions.

Writing custom cryptographic verification unnecessarily. A maintained WebAuthn server library is usually a safer choice than implementing the specification directly.

13. Should every website replace passwords immediately?

Not necessarily.

Passkeys can improve both usability and security, but migration strategy matters.

For a new application, passwordless registration may be a reasonable default if the product has a well-designed recovery flow and supports its target platforms.

For an existing application with thousands of users, incremental adoption is often safer.

Start by allowing authenticated users to register passkeys in account settings.

Then add passkey login alongside the existing authentication system.

Introduce conditional mediation where supported.

Measure registration success, authentication failures, device compatibility and recovery requests.

Finally, consider making passkeys the preferred authentication method once the user experience and recovery mechanisms are sufficiently mature.

A phased rollout also makes it easier to identify browser-specific issues without locking legitimate users out.

14. A production readiness checklist

Before enabling passkeys in production, verify the following:

  • All WebAuthn operations run in an appropriate secure context.
  • RP IDs and trusted origins are explicitly configured.
  • Challenges are cryptographically random, short-lived and single-use.
  • Registration requires appropriate account authorization.
  • Server-side verification follows the WebAuthn specification.
  • Public keys and credential identifiers are stored safely.
  • Login establishes a session only after successful verification.
  • User-verification requirements are enforced on the server.
  • Credential removal and account recovery are protected.
  • Multiple credentials per account are supported where appropriate.
  • Authentication failures and security-sensitive account changes are monitored.
  • Mobile, desktop, cross-device and hardware-key scenarios are tested.

These checks matter more than whether the frontend can display an attractive biometric login prompt.

Conclusion: passkeys are an authentication architecture, not just a browser feature

WebAuthn makes public-key authentication accessible to ordinary web applications.

Modern browser APIs have removed much of the serialization work that previously made passkey integration cumbersome.

But the browser is only one part of the system.

The real implementation work lies in challenge management, server-side verification, credential storage, domain configuration, account recovery and secure user journeys.

For developers building modern applications in PHP, JavaScript, Python or other backend environments, passkeys are increasingly worth considering as a practical alternative to traditional passwords.

The best starting point is not to replace an entire authentication system overnight.

It is to implement one complete, correctly verified registration and login flow, then build a secure migration strategy around it.