CSRF protection with a React Form, a Flask server, and Flask-WTF
You'll need to send the csrf token as the header X-CSRFToken
when you POST the form. See their docs here: http://flask-wtf.readthedocs.io/en/stable/csrf.html#javascript-requests
Their example w/ POSTing via jQuery sets the X-CSRFToken
before sending any POST/PUT/DELETE ajax requests:
<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>
Depending on what library you're using to send the form POSTs back to the server, your implementation of setting the header X-CSRFToken
will be different.
You can throw {{ csrf_token() }} in a meta tag in index.html
<meta id="csrf-token" content={{csrf_token()}}>
then when you wanna post/fetch, just add it to ur headers with
export const post = (path, data={}) => {
const options = {
method: 'POST',
headers: {
// 'Accept': 'application/json; charset=utf-8',
// 'Content-Type': 'application/json; charset=utf-8',
// 'Cache': 'no-cache',
// 'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': document.getElementById("csrf-token").getAttribute("content")
},
body: data
};
return fetch(path, options);
}
p.s. this still feels hacky and I'm still looking for a more reacty way