Home / Notes

Passkeys with SimpleWebAuthn

SimpleWebAuthn is a pair of complimentary libraries for making things a bit easier when implementing passkeys. There is a lib for the browser, and a lib for the server.

There's quite a bit of code involved with making this happen, but I'll try and make it as simple and minimal as possible. Please let me know if there's anything I can improve!

Database

Let's start with the database schema. You'll need the following table to hold the public keys and tie them to users.

create table passkeys (
  id text not null,
  user_id uuid not null,
  public_key text not null,
  counter integer not null default 0,
  transports text null,
  device_type text null,
  backed_up boolean not null default false,
  created_at timestamp without time zone not null default now(),
  constraint passkeys_pkey primary key (id),
  constraint passkeys_user_id_users_id_fk foreign KEY (user_id) references users (id) on delete CASCADE
);

Client functions

Now to where where all the magic happens: the browser. For the two main actions possible in the authentication, I've got two functions, one for signing up and one for signing in. They both follow the same pattern:

  1. Get options from the server.
  2. Fire off a SimpleWebAuthn function to recieve the attestation/assertions.
  3. Verify the action on the server against the attestation/assertion.
import {
  startAuthentication,
  startRegistration,
  type PublicKeyCredentialCreationOptionsJSON,
  type PublicKeyCredentialRequestOptionsJSON,
} from "@simplewebauthn/browser";

async function handleSignUp(form: HTMLFormElement) {
  const optionsJSON = await fetch<PublicKeyCredentialCreationOptionsJSON>(
    "/register/options",
    { method: "post", body: new FormData(form) },
  );
  const attestation = await startRegistration({ optionsJSON });
  await fetch("/register/verify", {
    method: "post",
    body: JSON.stringify(attestation),
  });
}

async function handleSignIn() {
  const optionsJSON = await fetch<PublicKeyCredentialRequestOptionsJSON>(
    "/authenticate/options",
    { method: "post" },
  );
  const assertion = await startAuthentication({ optionsJSON });
  await fetch("/authenticate/verify", {
    method: "post",
    body: JSON.stringify(assertion),
  });
}

You want to fire these off on the button click, for registration you probably at least want a simple form with an input to collect a unique ID for the user.

Server functions

Now let's create those routes that the client JS expects to hit: /register/options, /register/verify, /authenticate/options, and /authenticate/verify. Use what you want for your backend, I'm going to write these examples as Astro functions.

Registration routes

// Route /register/options.ts
import { relyingParty, saveChallenge } from "@/library/auth";
import { generateAuthenticationOptions } from "@simplewebauthn/server";
import type { APIRoute } from "astro";

export const POST: APIRoute = async ({ cookies, request }) => {
  const { rpID, secure } = relyingParty(request);
  const options = await generateAuthenticationOptions({
    rpID,
    userVerification: "required",
  });
  saveChallenge(cookies, options.challenge, undefined, secure);
  return new Response(JSON.stringify(options));
};

You'll notice I'm importing some common functions from @/library/auth that are used in these backend routes. You can see these functions here.

// Route /register/verify.ts
import {
  CHALLENGE_COOKIE,
  readChallenge,
  relyingParty,
  startSession,
} from "@/library/auth";
import { getPasskey, updatePasskeyCounter } from "@/library/database";
import {
  verifyAuthenticationResponse,
  type AuthenticatorTransportFuture,
} from "@simplewebauthn/server";
import type { APIRoute } from "astro";

export const POST: APIRoute = async ({ cookies, request }) => {
  const { rpID, origin, secure } = relyingParty(request);
  const saved = readChallenge(cookies);
  if (!saved) return new Response("Login expired.", { status: 400 });
  const response = await request.json();
  const passkey = await getPasskey(response.id);
  if (!passkey) return new Response("Unknown passkey.", { status: 400 });
  const { verified, authenticationInfo } = await verifyAuthenticationResponse({
    response,
    expectedChallenge: saved.challenge,
    expectedOrigin: origin,
    expectedRPID: rpID,
    credential: {
      id: passkey.id,
      publicKey: Uint8Array.from(Buffer.from(passkey.publicKey, "base64url")),
      counter: passkey.counter,
      transports: passkey.transports?.split(",") as
        AuthenticatorTransportFuture[] | undefined,
    },
  });
  if (!verified) return new Response("Invalid passkey.", { status: 400 });
  await updatePasskeyCounter(passkey.id, authenticationInfo.newCounter);
  cookies.delete(CHALLENGE_COOKIE, { path: "/" });
  startSession(cookies, passkey.user, secure);
  return new Response(JSON.stringify({ verified: true }));
};

This file also imports from a database library, you'll need to write your own database interactions.

Authentication routes

Now for the authentication routes, prepare for the final wall of code.

// Route /authenticate/options.ts
import { relyingParty, saveChallenge } from "@/library/auth";
import { getUser } from "@/library/database";
import { userSchema } from "@/library/validation";
import { generateRegistrationOptions } from "@simplewebauthn/server";
import type { APIRoute } from "astro";

export const POST: APIRoute = async ({ cookies, request }) => {
  const { rpID, secure } = relyingParty(request);
  const user = userSchema.parse(await request.formData());
  if (await getUser(user.id))
    return new Response("Name already taken.", { status: 409 });
  const options = await generateRegistrationOptions({
    rpName: "SocialList",
    rpID,
    userName: user.email,
    attestationType: "none",
    authenticatorSelection: {
      residentKey: "required",
      userVerification: "required",
    },
  });
  saveChallenge(cookies, options.challenge, name, secure);
  return new Response(JSON.stringify(options));
};

I'm importing a validation function to validate incoming data.

// Route /authenticate/verify.ts
import {
  CHALLENGE_COOKIE,
  readChallenge,
  relyingParty,
  startSession,
} from "@/library/auth";
import { createPasskey, createUser } from "@/library/database";
import { verifyRegistrationResponse } from "@simplewebauthn/server";
import type { APIRoute } from "astro";

export const POST: APIRoute = async ({ cookies, request }) => {
  const { rpID, origin, secure } = relyingParty(request);
  const saved = readChallenge(cookies);
  if (!saved) return new Response("Registration expired.", { status: 400 });
  const { verified, registrationInfo } = await verifyRegistrationResponse({
    response: await request.json(),
    expectedChallenge: saved.challenge,
    expectedOrigin: origin,
    expectedRPID: rpID,
  });
  if (!verified) return new Response("Invalid passkey.", { status: 400 });
  const { credential, credentialDeviceType, credentialBackedUp } =
    registrationInfo;
  const [user] = await createUser({ name: saved.name });
  await createPasskey({
    id: credential.id,
    userID: user.id,
    publicKey: Buffer.from(credential.publicKey).toString("base64url"),
    counter: credential.counter,
    transports: credential.transports?.join(","),
    deviceType: credentialDeviceType,
    backedUp: credentialBackedUp,
  });
  cookies.delete(CHALLENGE_COOKIE, { path: "/" });
  startSession(cookies, user, secure);
  return new Response(JSON.stringify({ verified: true }));
};

And just like that, passkeys.