Skip to content
jshacks.dev
Security

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.

1 min read
Summarize in AI

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.

register.jsJavaScript
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);
Text
public-key true

The 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.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.