Web Authentication API

29 July 2025

Updated: 29 July 2025

The Web Authentication API is a public/private key based authentication mechanism that is built into modern browsers and enables us to easily develop authentication solutions on the web

It consists of a few simple APIs, namely navigator.credentials.get and navigatior.credentials.create. A simple example that uses these APIs can be seen below:

Example

Code

And the code that implements the above can be seen as follows

1
let creds: Credential | null
2
3
const createButton = document.createElement('button')
4
createButton.innerText = "Create Account"
5
createButton.onclick = async () => {
6
const newCreds = await createCredentials()
7
alert("Created credentials are" + JSON.stringify(newCreds))
8
9
creds = newCreds
10
}
11
12
const loginButton = document.createElement('button')
13
loginButton.innerText = "Log In"
14
loginButton.onclick = async () => {
15
if (!creds) {
16
throw new Error("Credentials not created")
17
}
18
19
const gotCreds = await getCredentials(creds.rawId)
20
alert("Loaded credentials are" + JSON.stringify(gotCreds))
21
}
22
23
document.querySelector<HTMLDivElement>('#authn-example')!.appendChild(createButton)
24
document.querySelector<HTMLDivElement>('#authn-example')!.appendChild(loginButton)
25
26
function getCredentials(id: BufferSource) {
27
return navigator.credentials.get({
28
publicKey: {
29
challenge: new Uint8Array([117, 61, 252, 231, 191, 241 /**/]),
30
rpId: window.location.host,
31
allowCredentials: [
32
{
33
id,
34
type: "public-key",
35
},
36
],
37
userVerification: "required",
38
}
39
})
40
}
41
42
function createCredentials() {
43
return navigator.credentials.create({
44
publicKey: {
45
challenge: new Uint8Array([117, 61, 252, 231, 191, 241 /**/]),
46
rp: { id: window.location.host, name: "Nabeel Credential Testing" },
47
user: {
48
id: new Uint8Array([79, 252, 83, 72, 214, 7, 89, 26]),
49
name: "jamiedoe",
50
displayName: "Jamie Doe",
51
},
52
pubKeyCredParams: [{ type: "public-key", alg: -7 }],
53
},
54
});
55
}
56
57
function sleep(ms = 2000) {
58
return new Promise((res) => setTimeout(res, ms))
59
}