could be used for various cases.
the following will validate biometric auth or register a new one.
(async () => {
try {
// Check if WebAuthn is supported in the browser
if (!window.PublicKeyCredential) {
console.log("WebAuthn is not supported in this browser.");
return;
}
// Create a random challenge (this would usually come from the server)
const challenge = new Uint8Array(32);
window.crypto.getRandomValues(challenge);
const publicKeyCredentialCreationOptions = {
challenge: challenge, // Random challenge from the server
rp: {
name: "Example Corp", // Name of your site/service
id: window.location.hostname
},
user: {
id: Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(16))), // User ID (must be unique per user)
name: "[email protected]", // Username/email for the user
displayName: "Example User"
},
pubKeyCredParams: [
{
type: "public-key",
alg: -7 // Algorithm, usually ECDSA with SHA-256
}
],
authenticatorSelection: {
authenticatorAttachment: "platform", // Use device's biometric (platform) authenticator
userVerification: "required"
},
timeout: 60000,
attestation: "direct" // Attestation type
};
// Register a new passkey if none exist
let credentials;
try {
credentials = await navigator.credentials.get({
publicKey: {
challenge: challenge,
rpId: window.location.hostname, // The relying party's domain (this website)
allowCredentials: [], // Empty to allow user to choose from any available credentials
userVerification: "required"
}
});
console.log("Biometric Authentication successful!");
console.log("Credential ID:", credentials.id);
} catch (error) {
console.log("No credentials found, attempting to create one.");
// If no credentials are available, we create a new one
const newCredential = await navigator.credentials.create({ publicKey: publicKeyCredentialCreationOptions });
// Store the credential for future logins (typically, you'd send this to a server)
console.log("New passkey created:", newCredential);
// Now that we've created a passkey, attempt to use it for authentication
credentials = await navigator.credentials.get({
publicKey: {
challenge: challenge,
rpId: window.location.hostname,
allowCredentials: [
{
id: newCredential.rawId,
type: "public-key",
transports: ["internal"]
}
],
userVerification: "required"
}
});
console.log("Biometric Authentication successful after creating passkey!");
console.log("Credential ID:", credentials.id);
}
} catch (error) {
// Log the error if authentication or registration fails
console.log("Error during authentication or registration:", error);
}
})();
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too