Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions examples.json
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,11 @@
],
"name": "notify-link-clicks-i18n"
},
{
"description": "Demonstrates the use of protocol handlers.",
"javascript_apis": [],
"name": "open-irc-links"
},
{
"description": "Adds a browser action icon to the toolbar. When the browser action is clicked, the add-on opens a page that was packaged with it.",
"javascript_apis": ["browserAction.onClicked", "tabs.create"],
Expand Down Expand Up @@ -621,8 +626,8 @@
"name": "window-manipulator"
},
{
"description": "Demonstrates the use of protocol handlers.",
"description": "Demonstrates how to use the Web Authentication API.",
"javascript_apis": [],
"name": "open-irc-links"
"name": "webauthn"
}
]
29 changes: 29 additions & 0 deletions webauthn/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# webauthn

This extension illustrates the use of [navigator.credentials.create()](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create) and [navigator.credentials.get()](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get) to create and validate credentials that a website can use to authenticate a user.

## What it does ##

The extension includes an action with a popup that includes HTML, CSS, and JavaScript.

When you click the action (toolbar button), the extension's popup opens, enabling you to:

* Paste a JSON file.
* Click a button to register the JSON using `navigator.credentials.create()`.
* Click a button to authenticate the JSON using `navigator.credentials.get()`.


When you click a button, the JavaScript reads the JSON file and, if needed, converts the challenge and user ID to an ArrayBuffer. It then runs the selected `navigator.credentials` method.

If you choose to register the JSON, you get either a confirmation or an error message, depending on the outcome.

If you choose to authenticate JSON, you get either details of the credential ID, authenticator data, client data JSON, and signature, or an error message if the authentication fails.

## What it shows ##

In this example, you see how to:

* Use an action (toolbar button) with a popup.
* Give a popup style and behavior using CSS and JavaScript.
* Convert strings in base64 to an ArrayBuffer.
* Execute `navigator.credentials.create()` and `navigator.credentials.get()`.
30 changes: 30 additions & 0 deletions webauthn/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"description": "Registers and authenticates WebAuthn credentials using options from the popover.",
"manifest_version": 3,
"name": "WebAuthn extension",
"version": "1.0",
"homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/webauthn",

"action": {
"default_popup": "popup.html",
"default_icon": {
}
},

"permissions": [
"storage"
],
Comment on lines +14 to +16
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rob--W is there any need for this? I can't see that we are using any APIs or features that need it. However, as I can't fully test the extension, I've not been able to confirm it's not needed for some reason.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed for this example, as the browser.storage API is not used anywhere.


"browser_specific_settings": {
"gecko": {
"id": "beastify@mozilla.org",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixup id please.

"data_collection_permissions": {
"required": ["none"]
}
}
},

"host_permissions": [
"https://*/*"
]
}
23 changes: 23 additions & 0 deletions webauthn/popup.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
body {
width: 400px; /* Set the desired width */
height: 300px; /* Set the desired height */
padding: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: Arial, sans-serif;
}

textarea {
width: 100%;
height: 100px;
margin-bottom: 10px;
}

button {
width: 100%;
padding: 10px;
margin: 5px 0;
cursor: pointer;
}
33 changes: 33 additions & 0 deletions webauthn/popup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebAuthn extension</title>
<style>
body {
font-family: sans-serif;
width: 300px;
padding: 10px;
}
textarea {
width: 100%;
height: 100px;
margin-bottom: 10px;
}
button {
margin: 5px 0;
width: 100%;
padding: 8px;
font-size: 14px;
}
</style>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<h1>WebAuthn</h1>
<textarea id="optionsText" placeholder='Enter options JSON here'></textarea>
<button id="registerButton">Register (navigator.credentials.create)</button>
<button id="authButton">Authenticate (navigator.credentials.get)</button>
<script src="popup.js"></script>
</body>
</html>
99 changes: 99 additions & 0 deletions webauthn/popup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
document.addEventListener('DOMContentLoaded', () => {
const registerButton = document.getElementById('registerButton');
const authButton = document.getElementById('authButton');
const optionsText = document.getElementById('optionsText');

// Helper function to convert a Base64 string to an ArrayBuffer
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please update the code example according to my review at mdn/content#43653 (review)

function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}

// Convert relevant options properties if they are Base64 strings
function convertOptions(options) {
// Convert challenge if it's a string
if (typeof options.challenge === 'string') {
options.challenge = base64ToArrayBuffer(options.challenge);
}
if (options.allowCredentials) {
options.allowCredentials = options.allowCredentials.map(cred => ({
...cred,
id: base64ToArrayBuffer(cred.id)
}));
}
// Optionally convert user.id if it's a string (depending on your use-case)
if (options.user && typeof options.user.id === 'string') {
options.user.id = base64ToArrayBuffer(options.user.id);
}
return options;
}

function arrayBufferToBase64(buffer) {
return btoa(String.fromCharCode(...new Uint8Array(buffer)));
}

// Handle WebAuthn registration
registerButton.addEventListener('click', async () => {
let options;
try {
options = JSON.parse(optionsText.value);
} catch (error) {
alert('Invalid JSON in text field');
return;
}

// Convert challenge (and user id if necessary)
options = convertOptions(options);

try {
const credential = await navigator.credentials.create({ publicKey: options });
console.log('Credential created:', credential);
alert('Credential created successfully');
} catch (err) {
console.error('Error during credential creation:', err);
alert('Error during credential creation: ' + err);
}
});



// Handle WebAuthn authentication
authButton.addEventListener('click', async () => {
let options;
try {
options = JSON.parse(optionsText.value);
} catch (error) {
alert('Invalid JSON in text field');
return;
}

// Convert challenge if necessary for authentication options as well
options = convertOptions(options);

try {
const assertion = await navigator.credentials.get({ publicKey: options });
console.log('Assertion obtained:', assertion);

const credentialId = assertion.id;
const authenticatorData = arrayBufferToBase64(assertion.response.authenticatorData);
const clientDataJSON = new TextDecoder().decode(assertion.response.clientDataJSON);
const signature = arrayBufferToBase64(assertion.response.signature);

alert(
`Assertion obtained successfully!\n\n` +
`Credential ID: ${credentialId}\n\n` +
`Authenticator Data: ${authenticatorData}\n\n` +
`Client Data JSON: ${clientDataJSON}\n\n` +
`Signature: ${signature}`
);
} catch (err) {
console.error('Error during credential assertion:', err);
alert('Error during credential assertion: ' + err);
}
});
});
Loading