WebAuthn is often introduced as “passwordless login”, but that description hides the engineering decisions that determine whether an implementation is secure, maintainable and usable. The browser API is relatively small. The difficult part is designing the registration and authentication ceremonies around it, then validating every value on the server instead of treating browser output as trustworthy.
WebAuthn lets a website use public-key credentials held by an authenticator. The private key remains with the authenticator; the site stores a public key and uses it to verify signed authentication responses. An authenticator might be a built-in fingerprint or face-recognition system, a device PIN, a USB security key or a credential synchronised by a platform password manager. The Web Authentication Level 3 Recommendation defines the API and its security model.
This makes WebAuthn useful for more than removing password fields. It can provide phishing-resistant multi-factor authentication, protect privileged administrative actions and reduce the burden of password resets. It also changes the shape of your application: credentials belong to a relying party, ceremonies are challenge-based, and recovery needs to be designed before the first user registers a passkey.
The mental model: browser, authenticator and relying party
There are three participants in a WebAuthn ceremony:
- The relying party is your service. It creates ceremony options, stores credential records and verifies responses.
- The client is usually a browser and operating system combination. It mediates access to authenticators and supplies the page origin.
- The authenticator creates or uses a public/private key pair and requires an authorisation gesture, such as a biometric check, PIN or physical interaction.
Your JavaScript does not receive the private key. During registration, it receives a credential containing an identifier, client data and an attestation object. During authentication, it receives an assertion containing a credential identifier, authenticator data and a signature. These values are normally sent to your server as base64url-encoded data.
Two pieces of scope are particularly important. The origin identifies the exact web application context, including scheme, host and port where applicable. The RP ID, or relying-party identifier, scopes credentials to a domain. They are related but not interchangeable. A site served from https://login.example.co.uk might use an RP ID of example.co.uk, subject to the browser’s domain rules, allowing suitable subdomains to participate. The server must still validate the exact origins it expects.
The WebAuthn specification explains that credentials are scoped to the RP ID and that the origin is included in signed client data. It also requires relying parties to validate the origin rather than accepting whatever the browser sends. Treat this as a server-side security requirement, not an optional diagnostic check.
Registration is a two-step ceremony
A robust registration flow has a server phase and a browser phase. The server first creates a fresh, unpredictable challenge and builds public-key credential-creation options. Those options normally include the relying-party name and ID, a user identifier, a display name, supported public-key algorithms, an authenticator-selection policy and an exclusion list for credentials already attached to the account.
The browser then calls navigator.credentials.create(). The user agent selects an authenticator and asks the user to authorise the operation. The resulting credential is returned to JavaScript and submitted to the server. The server verifies the response before storing the credential’s public key.
A simplified browser-side registration function might look like this:
function base64urlToBytes(value) {
const padding = '='.repeat((4 - value.length % 4) % 4);
const base64 = (value + padding)
.replaceAll('-', '+')
.replaceAll('_', '/');
const binary = atob(base64);
return Uint8Array.from(binary, character => character.charCodeAt(0));
}
function bytesToBase64url(buffer) {
const bytes = new Uint8Array(buffer);
let binary = '';
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary)
.replaceAll('+', '-')
.replaceAll('/', '_')
.replaceAll('=', '');
}
async function registerWebAuthn() {
const response = await fetch('/webauthn/registration/options', {
method: 'POST',
headers: { 'Accept': 'application/json' },
credentials: 'same-origin'
});
if (!response.ok) {
throw new Error('Could not obtain registration options');
}
const options = await response.json();
options.challenge = base64urlToBytes(options.challenge);
options.user.id = base64urlToBytes(options.user.id);
if (options.excludeCredentials) {
options.excludeCredentials = options.excludeCredentials.map(credential => ({
...credential,
id: base64urlToBytes(credential.id)
}));
}
const credential = await navigator.credentials.create({
publicKey: options
});
const result = {
id: credential.id,
rawId: bytesToBase64url(credential.rawId),
type: credential.type,
response: {
clientDataJSON: bytesToBase64url(
credential.response.clientDataJSON
),
attestationObject: bytesToBase64url(
credential.response.attestationObject
)
}
};
const verification = await fetch('/webauthn/registration/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'same-origin',
body: JSON.stringify(result)
});
if (!verification.ok) {
throw new Error('Registration failed');
}
return verification.json();
}
The conversion code is deliberately explicit. WebAuthn values are binary, whereas JSON transports strings. In production, use a well-maintained WebAuthn server library where possible, but understand the encoding it expects. A common implementation failure is converting the challenge or credential ID incorrectly, particularly by using ordinary base64, URL-decoding at the wrong stage or treating binary data as UTF-8 text.
Choosing registration options
Do not copy an authenticator policy from an unrelated application. Start with the user experience you actually need.
residentKeycontrols whether the credential is discoverable by the authenticator. Discoverable credentials are central to username-less sign-in and are commonly associated with passkeys.userVerificationdescribes whether the authenticator should verify the user locally.preferredprovides a balance between security and compatibility;requiredis appropriate when you must know that a local verification step occurred.authenticatorAttachmentcan restrict platform or cross-platform authenticators, but unnecessary restrictions can exclude users and create confusing prompts.excludeCredentialsprevents a user from registering the same authenticator credential repeatedly for the same account.
For most consumer services, allowing both platform and roaming authenticators is more inclusive than forcing one category. For an organisation that issues hardware security keys, a stricter policy may be justified, but document the operational consequences before deployment.
Authentication proves possession of the private key
Authentication begins with another server-generated challenge. The server may identify the account first and provide an allowCredentials list containing the credential IDs registered to that account. Alternatively, it can use a discoverable credential and allow the authenticator to select the account, which supports a username-less flow.
The browser calls navigator.credentials.get(), the user authorises the operation, and the response is sent to the server. A basic assertion request can be prepared like this:
async function authenticateWebAuthn(options) {
options.challenge = base64urlToBytes(options.challenge);
if (options.allowCredentials) {
options.allowCredentials = options.allowCredentials.map(credential => ({
...credential,
id: base64urlToBytes(credential.id)
}));
}
const credential = await navigator.credentials.get({
publicKey: options
});
const assertion = {
id: credential.id,
rawId: bytesToBase64url(credential.rawId),
type: credential.type,
response: {
clientDataJSON: bytesToBase64url(
credential.response.clientDataJSON
),
authenticatorData: bytesToBase64url(
credential.response.authenticatorData
),
signature: bytesToBase64url(
credential.response.signature
)
}
};
if (credential.response.userHandle) {
assertion.response.userHandle = bytesToBase64url(
credential.response.userHandle
);
}
const response = await fetch('/webauthn/authentication/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'same-origin',
body: JSON.stringify(assertion)
});
if (!response.ok) {
throw new Error('Authentication failed');
}
return response.json();
}
The signature is not a standalone password replacement. It covers the authenticator data and a hash of the client data, including the challenge. The server must recover the stored public key for the credential ID and verify the signature over the correct bytes. It must also ensure that the challenge is the one issued for this ceremony and has not already been consumed.
What the server must validate
Server-side verification is the security boundary. The browser can help collect the response, but it cannot be trusted to decide whether the response is valid. At a minimum, registration and authentication should validate the following.
- Transport and origin. Require HTTPS in production and compare the client-data origin against an explicit allow-list. Do not accept arbitrary subdomains simply because they happen to end with your domain. A compromised subdomain can become relevant to your authentication boundary.
- Challenge. Look up the challenge in server-side session or short-lived storage, bind it to the intended operation and account where applicable, enforce an expiry and invalidate it after one attempt. A challenge should never be accepted twice.
- RP ID hash. Parse authenticator data and compare its RP ID hash with the SHA-256 hash of the RP ID you expected. This prevents a credential scoped to another relying party from being accepted accidentally.
- Flags. Check user presence where required. If your policy requires local verification, require the user-verification flag as well. Do not assume that a biometric prompt occurred merely because a platform authenticator was used.
- Credential identity. During authentication, find the credential by its identifier and confirm that it belongs to the account being authenticated. During registration, ensure the credential ID is unique for the relevant relying party.
- Signature. Verify the assertion signature using the stored public key and the precise authenticator data and client-data hash defined by WebAuthn.
- Algorithm and parsing. Accept only algorithms and authenticator-data structures supported by your chosen verification library. Reject malformed or truncated binary values rather than trying to repair them.
The W3C assertion-verification algorithm is the authoritative reference for the sequence and conditions. A server library can perform the cryptographic work, but your application still needs to configure expected origins, RP ID, challenge storage, account binding and policy correctly.
Attestation is not always necessary
Registration responses can include attestation data describing the authenticator. Many services do not need to identify the make or model of a user’s authenticator. In that case, a privacy-preserving attestation policy is usually simpler and avoids unnecessary device metadata.
Attestation becomes more relevant when an organisation needs to enforce an approved hardware inventory, meet a specific assurance requirement or distinguish managed authenticators. It adds operational complexity: certificate chains, metadata, policy decisions and possible compatibility problems. Do not enable strict attestation merely because it appears in an example.
Passkeys, discoverability and account selection
“Passkey” is commonly used for a discoverable WebAuthn credential that can be used across devices or platforms, depending on the authenticator and synchronisation provider. WebAuthn is the web API; passkeys are a user-facing credential experience built using WebAuthn and related authenticator protocols. The passkeys.dev specification overview describes how WebAuthn and CTAP fit together.
Discoverable credentials improve the login experience because the user may not need to type an identifier. They also change your data model. Your account lookup can be driven by the credential ID and optional user handle rather than an email address. You still need a careful policy for account linking: never attach a newly verified credential to an account selected only from untrusted client input.
For a username-less flow, show a clear “Sign in with a passkey” action and use conditional mediation where supported. Feature-detect it rather than assuming that every browser provides the same UI. The MDN Web Authentication API reference is useful for browser-facing API details, but the W3C specification remains the source for normative verification behaviour.
Recovery is part of the design
A passwordless system still needs recovery. Users lose phones, replace laptops, remove credentials accidentally and change jobs. If your only recovery mechanism is a weak email link, an attacker may simply target that link instead of the passkey.
Offer more than one carefully considered route, such as registering multiple passkeys, adding a hardware security key, using an organisation-controlled recovery process or requiring existing strong authentication before adding a new credential. Recovery should be auditable and should notify the user through an independent channel.
Avoid displaying a raw credential ID as if it were a friendly device name. Store metadata such as creation time, last-used time, authenticator attachment when available and a user-supplied label. The label helps account management, but it is not proof of what the authenticator physically is.
Security pitfalls that appear in production
- Accepting the browser’s account decision. The server must determine which credential and account are valid. Never trust a client-supplied user ID to select the account after verification.
- Reusing challenges. A challenge stored indefinitely or shared between sessions creates replay risk. Use short-lived, single-use records.
- Mixing environments. Development, staging and production should normally use distinct RP IDs and origins. A credential registered for one environment should not silently become valid for another.
- Changing domains casually. Moving from
example.comtologin.example.com, or introducing a new parent domain, can affect RP ID scope and existing credentials. Plan migrations and test every browser and authenticator combination you support. - Using insecure contexts. WebAuthn is intended for secure contexts. Local development can use a trusted local HTTPS setup or browser-supported localhost behaviour, but production must use correctly configured TLS.
- Ignoring permissions policy and framing. If your login interface is embedded, check the browser’s rules for WebAuthn in iframes and the
publickey-credentials-createpermissions policy. Prefer a top-level authentication page unless you have a documented cross-origin design. - Logging sensitive ceremony data. Avoid logging complete client data, authenticator data and account identifiers together. Keep operational logs useful without turning them into a replay or privacy liability.
Performance, accessibility and operations
WebAuthn itself is usually a small part of the request budget. The larger delays often come from extra account lookups, session storage, cross-device hand-off and a slow authentication endpoint. Generate options from a fast endpoint, keep challenges in a low-latency store and avoid loading an entire user profile before credential verification.
Do not set aggressive client-side timeouts. Users may need to unlock a phone, insert a security key or approve a prompt on another device. The browser can report errors such as cancellation or timeout; present a recoverable message and allow the user to try again without losing the whole login form.
Accessibility requires more than adding a passkey button. Provide a keyboard-operable control, a useful accessible name and instructions that do not assume a particular biometric. Explain that the user may be asked for a device PIN, security key touch or screen lock. Keep a conventional route for users whose browser, assistive technology or organisational policy does not support your preferred flow.
Test registration and authentication on the actual combinations you support: desktop platform authenticators, mobile devices, external security keys, private browsing where relevant, account switching and a newly replaced device. Use WebDriver’s WebAuthn virtual-authenticator support for repeatable automated tests, then supplement it with real-device testing because platform UI and account synchronisation behaviour are not fully represented by a virtual authenticator.
A sensible implementation sequence
- Write down the exact production origins and RP ID before building the UI.
- Choose a server-side WebAuthn library with active maintenance and clear support for your language.
- Implement challenge generation, storage, expiry and single-use invalidation first.
- Build registration and authentication endpoints with strict origin and RP ID configuration.
- Start with ordinary platform and external authenticators rather than imposing narrow restrictions.
- Add credential management, multiple credentials and a recovery process before making passwords optional.
- Instrument failure reasons without logging private ceremony payloads.
- Test account binding, replay attempts, wrong-origin responses, expired challenges, duplicate registration and recovery abuse.
WebAuthn is powerful because the browser and authenticator enforce important cryptographic boundaries. It is not magic, though. The application still controls the origin allow-list, challenge lifecycle, account association, recovery process and user experience. Treat those decisions as part of the authentication protocol, not as surrounding application code, and WebAuthn becomes a practical foundation for secure sign-in rather than just another button on the login page.