Skip to content

Async csrf improvements #17054

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: 5.x
Choose a base branch
from
Draft
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
48 changes: 34 additions & 14 deletions src/templates/_special/async-csrf-input.twig
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@
<script>
(function() {
fetch('{{ url }}', {
headers: {
'Accept': 'application/json',
function fetchCsrfData() {
return fetch('{{ url }}', {
headers: {
'Accept': 'application/json',
},
}).then((response) => response.json());
}

function createHiddenInput({name, value}) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
return input;
}

function handleFocusIn(e) {
const asyncInput = e.currentTarget.querySelector('craft-csrf-input');
if (asyncInput) {
fetchCsrfData().then(({csrfTokenName, csrfTokenValue}) => {
const input = createHiddenInput({name: csrfTokenName, value: csrfTokenValue});
asyncInput.replaceWith(input);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we also need to defer/debounce submit events that come in between focusin and injecting the input.

Over a slow connection, you could interact with the form and submit before the CSRF has been injected, resulting in a CSRF error.

}
}).then(response => response.json())
.then(data => {
document.querySelectorAll('craft-csrf-input')
.forEach(element => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = data.csrfTokenName;
input.value = data.csrfTokenValue;
element.replaceWith(input);
});
});
}

const asyncInputs = document.querySelectorAll('craft-csrf-input');
asyncInputs.forEach((el) => {
const form = el.closest('form');
if (!form) {
console.warning('craft-csrf-input should be within a form element.');
return;
}
form.addEventListener('focusin', handleFocusIn);
});
})();
</script>