Register a passkey with WebAuthn
Start a passkey registration in the browser with navigator.credentials.create and a server-provided challenge, then send the result to your server.
A passkey is a WebAuthn credential. Registration asks the browser to create a key pair on the device, keeps the private key there and gives you the public key to store.
const options = await fetch('/webauthn/register/options').then((r) => r.json());
const credential = await navigator.credentials.create({
publicKey: {
challenge: Uint8Array.fromBase64(options.challenge, { alphabet: 'base64url' }),
rp: { name: 'Example', id: 'example.com' },
user: {
id: Uint8Array.fromBase64(options.userId, { alphabet: 'base64url' }),
name: '[email protected]',
displayName: 'Ana',
},
pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
},
});
console.log(credential.type, credential.id.length > 0);public-key trueThe server generates the random challenge and later checks it in the signed response, which prevents replay. alg: -7 is ES256 and -257 is RS256. residentKey: 'required' makes the credential discoverable, which is what lets the user sign in without typing a name. The request runs only on a secure origin, and rp.id must be your domain or a parent of it. See the MDN WebAuthn guide.
Verify the response on the server with a library such as SimpleWebAuthn, never by hand. Uint8Array.fromBase64 needs a recent browser; use a small helper where it is missing.