Belajar
← All lessons

How passkeys work

Make a passkey

Your device
Browser
shop.test

browser.js

const options = await post("/register/start", { name }); // the device makes a new key pair for this siteconst cred = await navigator.credentials.create({  publicKey: {    challenge: options.challenge,    rp: { id: "shop.test" },    user: { id: options.userId, name },    pubKeyCredParams: [{ type: "public-key", alg: -7 }],  },}); await post("/register/finish", cred);

server.js

app.post("/register/start", (req, res) => {  req.session.challenge = randomBytes(32);  res.json({ challenge: req.session.challenge, userId });}); app.post("/register/finish", async (req, res) => {  const { id, publicKey } = await verifyRegistration(req.body, req.session.challenge);  await db.keys.insert({ user, id, publicKey });});

Sign in with it by signing a challenge

Your device
Browser
shop.test

browser.js

const { challenge } = await post("/login/start"); // you unlock the device, it signs with the private keyconst assertion = await navigator.credentials.get({  publicKey: { challenge, rpId: "shop.test" },}); await post("/login/finish", assertion);

server.js

app.post("/login/start", (req, res) => {  req.session.challenge = randomBytes(32);  res.json({ challenge: req.session.challenge });}); app.post("/login/finish", async (req, res) => {  const key = await db.keys.find(req.body.id);  await finishLogin(key, req.body, req.session);  res.json({ user: key.user });});

Try to break it and the server says no

The server receivesRealReplayedEditedFake site

expects
Assertion

Without your private key, nobody can make a new valid signature

server.js

async function finishLogin(key, assertion, session) {  const { clientData, signature } = assertion;  const ok = await crypto.subtle.verify(    { name: "ECDSA", hash: "SHA-256" }, key.publicKey, signature, signedData,  );  if (!ok) throw new Error("bad signature");  if (clientData.challenge !== session.challenge) {    throw new Error("old challenge");  }  if (clientData.origin !== "https://shop.test") {    throw new Error("wrong site");  }  session.challenge = null; // used once}

Topics

Next: How hashing works

Open lesson