Register and sign in with a passkey
Register and sign in with a passkey: the browser half of WebAuthn, its payloads shown.
Apache-2.0Runs locally
Package: @awacloud/fw
A passkey made by this example would be bound to this site, so the example runs from a local copy: the steps are in the guide below.
The browser half of WebAuthn: detect support, register a passkey, sign in with it, and show the base64url payloads a server would verify.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
Passwordless sign-in, or a second factor, for a site that has a server to verify the replies. The browser never checks a signature: it asks the device and hands the result over. Without a server, this page shows that hand-over and stops there.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). WebAuthn needs https orlocalhost. - Copy
index.htmlandmain.jsnext to each other and open the page throughlocalhost(withnode serve.js,http://localhost:3124/fw/dom-webauthn/): the relying party id must be a domain name, so127.0.0.1is refused. The../../_style/examples.csslink is optional: copy that file along, or delete the link.
Registering creates a real passkey for localhost on your device or in
your password manager. Delete it afterwards from your browser's or
system's passkey settings.
What it shows
webauthn.support(): whether WebAuthn is there at all, and whether the device has a built-in authenticator. The buttons stay disabled until it answers.webauthn.register({ rp, user, authenticatorSelection }): the relying party id is the page's host; the user handle is 16 random bytes from fwrandom, never an email address or other personal data.webauthn.authenticate({ rpId, allowCredentials }): signs in with the credential just registered.- Both return plain objects with every binary field in base64url, ready to send as JSON.
- The challenge: fw generates one when none is given, which is all a page without a server can do. In production the server issues the challenge and checks that the reply signs it; a challenge made in the browser proves nothing.
NotAllowedErrorcovers both a cancelled prompt and a timeout; the page says so in its own words.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { webauthn } from '@awacloud/fw/dom/utils/webauthn.js';
fw.runtime.registerAllDeep([webauthn]);
const WEBAUTHN = fw.runtime.resolve('webauthn');
const RANDOM = fw.runtime.resolve('random'); // registered as a webauthn dependency
/** @param {string} id */
const el = (id) => /** @type {HTMLElement} */ (document.getElementById(id));
const registerButton = /** @type {HTMLButtonElement} */ (el('register'));
const signInButton = /** @type {HTMLButtonElement} */ (el('signin'));
const status = el('status');
/** The credential id a server would store with the public key; Sign in names it. */
let credentialId = '';
/** Show what goes to the server. @param {string} label @param {object} data */
function show(label, data) {
status.textContent = label;
el('payload').textContent = JSON.stringify(data, null, 2);
}
/** Say why a ceremony stopped: cancelling and timing out share one error name. @param {string} what */
const failed = (what) => (/** @type {Error} */ err) => {
status.textContent = err.name === 'NotAllowedError'
? `${what} cancelled or timed out.`
: `${what} did not finish: ${err.message}`;
};
// Feature detection first: without WebAuthn, the buttons stay disabled with a reason.
WEBAUTHN.support().then((/** @type {Record<string, boolean>} */ support) => {
if (!support.available) {
status.textContent = 'No WebAuthn here: it needs https or localhost.';
return;
}
// The relying party id is a domain name: an IP address (127.0.0.1, [::1]) is refused.
if (/^[\d.]+$|^\[/.test(location.hostname)) {
status.textContent = `WebAuthn needs a domain name: open this page at localhost, not ${location.hostname}.`;
return;
}
registerButton.disabled = false;
el('support').textContent = support.userVerifyingPlatformAuthenticator
? 'This device has a built-in authenticator (fingerprint, face or PIN).'
: 'No built-in authenticator: a security key or a phone can answer.';
});
// No server here, so fw generates each challenge; in production the server sends it, then checks the reply.
registerButton.addEventListener('click', () => {
WEBAUTHN.register({
rp: { id: location.hostname, name: 'awa examples' },
user: { id: RANDOM.bytes(16), name: 'reader@example.org', displayName: 'Example reader' },
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
})
.then((/** @type {{ id: string }} */ credential) => {
credentialId = credential.id;
signInButton.disabled = false;
show('Registered. Your server checks this and stores the public key:', credential);
})
.catch(failed('Registration'));
});
signInButton.addEventListener('click', () => {
WEBAUTHN.authenticate({ rpId: location.hostname, allowCredentials: [credentialId] })
.then((/** @type {object} */ assertion) => {
show('Signed in. Your server verifies the signature with the stored public key:', assertion);
})
.catch(failed('Sign-in'));
});index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Register and sign in with a passkey</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Register and sign in with a passkey</h1>
<p>The browser half of WebAuthn: this page asks your device for a passkey and shows what it would send
to a server. Nothing is verified here; that is the server's job.</p>
<p id="support"></p>
<!-- Disabled until feature detection answers. -->
<button id="register" type="button" disabled>Register a passkey</button>
<button id="signin" type="button" disabled>Sign in with it</button>
<p id="status" role="status"></p>
<pre id="payload"></pre>
</main>
</body>
</html>