webauthn_server_clients/client-node-vite/webauthn-client.js
2025-12-07 15:17:29 +01:00

90 lines
3.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
startRegistration,
startAuthentication
//} from 'https://cdn.jsdelivr.net/npm/@simplewebauthn/browser/+esm';
} from '@simplewebauthn/browser';
const API_BASE = 'https://auth.patachina.it';
function getUsername() {
return document.getElementById('username').value.trim();
}
async function registerUser() {
try {
const username = getUsername();
const resp = await fetch(`${API_BASE}/my/register-options`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ username: 'fabio' }),
body: JSON.stringify({ username }),
credentials: 'include',
});
const options = await resp.json();
const attResp = await startRegistration(options);
console.log('attResp: ',attResp);
const payload = {
username: 'fabio',
attestationResponse: attResp
};
console.log(payload);
const verif = await fetch(`${API_BASE}/my/register-verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
credentials: 'include',
})
const verification = await verif.json();
console.log('verification: ', verification);
alert(`Registrazione: ${verification.success ? 'OK' : 'Fallita'}`);
} catch (err) {
console.error(err);
alert('Errore nella registrazione');
}
}
async function loginUser() {
try {
const username = getUsername();
const resp = await fetch(`${API_BASE}/my/login-options`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
/* body: JSON.stringify({
username: 'fabio',
}, // tutto loggetto di risposta
), */
body: JSON.stringify({ username }),
credentials: 'include',
});
const options = await resp.json();
if (!resp.ok) {
// Qui uso il campo message inviato dal server
throw new Error(options.message || 'Errore sconosciuto');
}
console.log('options: ',options);
const authResp = await startAuthentication(options);
console.log('authResp: ',authResp);
const verif = await fetch(`${API_BASE}/my/login-verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(
{username: 'fabio',
assertionResponse: authResp}, // tutto loggetto di risposta
),
credentials: 'include',
});
const verification = await verif.json();
console.log('verification: ', verification);
//alert(JSON.stringify(verification));
alert(`Login: ${verification.success ? 'OK' : 'Fallito'}`);
} catch (err) {
console.error(err);
alert(`Login fallito: ${err.message}`);
}
}
document.getElementById('registerBtn').addEventListener('click', registerUser);
document.getElementById('loginBtn').addEventListener('click', loginUser);