-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
webAuthnAssert.js
83 lines (67 loc) · 3.09 KB
/
webAuthnAssert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* https://simplewebauthn.dev/docs/packages/browser/#startauthentication
*/
(() => {
"use strict";
const { startAuthentication } = SimpleWebAuthnBrowser;
const assertWebAuthn = document.getElementById("assertWebAuthn");
const webAuthnResponse = document.getElementById("webAuthnResponse");
// start authentication when the user clicks a button
assertWebAuthn.addEventListener("click", async () => {
// reset success/error messages
webAuthnResponse.innerText = "";
// grab the username from the form for now (todo: webauthn autofill)
// https://simplewebauthn.dev/docs/packages/browser/#browsersupportswebauthnautofill
let username = $("#username").val();
if (!username) {
webAuthnResponse.classList.remove("success");
webAuthnResponse.classList.add("failure");
webAuthnResponse.innerText = "Please fill out the username field before attempting a WebAuthn login";
return;
}
// GET authentication options from the endpoint that calls
// @simplewebauthn/server -> generateAuthenticationOptions()
const assertionRequest = await fetch("/api/internal/webAuthn/assertionRequest/" + username, {
method: "GET",
headers: {
"Content-Type": "application/vnd.api+json",
"Authorization": "Bearer " + frontendHash,
},
});
let assertionRequestJson;
try {
// pass the options to the authenticator and wait for a response
assertionRequestJson = await startAuthentication(await assertionRequest.json());
} catch (error) {
// some basic error handling
webAuthnResponse.classList.remove("success");
webAuthnResponse.classList.add("failure");
webAuthnResponse.innerText = error;
throw error;
}
// POST the response to the endpoint that calls
// @simplewebauthn/server -> verifyAuthenticationResponse()
const assertionResponse = await fetch("/api/internal/webAuthn/assertionResponse", {
method: "POST",
headers: { "Content-Type": "application/vnd.api+json" },
body: JSON.stringify(assertionRequestJson),
});
// wait for the results of verification
const assertionResponseJson = await assertionResponse.json();
// show UI appropriate for the `verified` status
if (assertionResponseJson && assertionResponseJson.publicKeyCredentialId) {
// redirect to homepage
setTimeout(function () {
webAuthnResponse.classList.remove("failure");
webAuthnResponse.classList.add("success");
webAuthnResponse.innerText = "Success! Logging you in...";
window.location = "/";
}, 1000);
} else {
// show an error message
webAuthnResponse.classList.remove("success");
webAuthnResponse.classList.add("failure");
webAuthnResponse.innerText = assertionResponseJson.data;
}
});
})();