1
votes

Can anyone guide me on how to use Flask-WTF CSRF protection when using Fetch? API docs doesnt seem to be clear on what to do with the CSRF token generated per request

I keep getting this error

The CSRF session token is missing.

and my javascript code:

let payload = {
            // some data,
          "X-CSRFToken": 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: 'same-origin',
                      })
                        .then(function(res) {
                            return res.json();
                        }).then(function(data) {
                          console.log(typeof(data))
                            return data.id
                        })
                    .catch(err => {
                      console.log(err);
                    });
            }
1
You have to add the CSRF token to your request as documented in flask-wtf.readthedocs.io/en/stable/… .Klaus D.
@KlausD. i actually did. it seems that its checking the session data. do also need to set the CSRF token in sessions? the errors states that "The CSRF session token is missing".Dr.DOOM

1 Answers

0
votes

use CSRF from Flask_cors and wrap your application in that. You won't need to use csrf_token explicitly then. Refer FLASK-CORS for usage.