According to the Flask-WTF documentation
this is how to pass the CSRF Token when using AJAX
<script type="text/javascript">
var csrf_token = "{{ csrf_token() }}";
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
</script>
Is there a way to implement the CSRF protection when using fetch API?
Also tried adding the credentials: 'include',
*Edit I am getting 2 errors:
the CSRF token is missing
The CSRF session token is missing
Here is my code
let csrf_token = "{{ csrf_token() }}";
let payload = {
// some data
"csrf_token": csrf_token
}
let header = { 'content-type': 'application/json','accept': 'application/json',"X-CSRFToken": csrf_token}
paypal.Buttons({
createOrder: function(data, actions) {
return fetch(prefix.concat("/payment/paypalCreate"), {
method: "POST",
headers: header ,
body:JSON.stringify(payload),
credentials: 'include',
})
.then(function(res) {
return res.json();
}).then(function(data) {
console.log(typeof(data))
return data.id
})
.catch(err => {
console.log(err);
});
}
I found a way around this and I don't know if anyone needs it but... I just passed the csrf token to the javascript function Here is my javascript.
function deleteUser(userId, csrf) {
fetch('/admin/deleteUser', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrf
},
body: JSON.stringify({
userId: userId
})
}).then(response => response.json())
.then(data => {
console.log('Success:', data);
window.location.href = data
})
}
<button onclick="deleteUser({{ User.id }}, '{{ csrf_token() }}')">
from flask_wtf.csrf import CSRFProtect
#depending on how you define app
#either
CSRFProtect(app)
#or
csrf = CSRFProtect()
csrf.init_app(app)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With