Invio di moduli personalizzati con protezione CSRF
Se l'utilizzo della libreria client granite.csrf.standalone
non è compatibile con il caso d'uso, è possibile aggiungere manualmente un token CSRF all'invio di un modulo. L’esempio seguente mostra come aggiungere un token CSRF all’invio di un modulo.
Questo frammento di codice illustra come, all'invio del modulo, il token CSRF può essere recuperato da AEM e aggiunto a un input di modulo denominato :cq_csrf_token
. Poiché il token CSRF ha una durata breve, è consigliabile recuperarlo e impostarlo immediatamente prima dell’invio del modulo, per garantirne la validità .
// Attach submit handler event to form onSubmit
document.querySelector('form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = event.target;
const response = await fetch('/libs/granite/csrf/token.json');
const json = await response.json();
// Create a form input named ``:cq_csrf_token`` with the CSRF token.
let csrfTokenInput = form.querySelector('input[name=":cq_csrf_token"]');
if (!csrfTokenInput?.value) {
// If the form does not have a CSRF token input, add one.
form.insertAdjacentHTML('beforeend', `<input type="hidden" name=":cq_csrf_token" value="${json.token}">`);
} else {
// If the form already has a CSRF token input, update the value.
csrfTokenInput.value = json.token;
}
// Submit the form with the hidden input containing the CSRF token
form.submit();
});