Search code examples
javascriptcookiesfetch-apix-xsrf-token

Best way to avoid HTTP 403 error when getting Set-Cookie header to set CSRF Cookie


I'm calling a REST API that has CSRF protection.

Everything works well. I'm getting the token and sending it back to the server.

However, when I do the very first request or when the CSRF Cookie is not set in the browser it always throws an HTTP 403 error.

This is because I didn't send CSRF token back given that this is the very first request in which the server sends the Set-Cookie header to set the CSRF Cookie.

What would be the best way to avoid this error the first time we send a request to a CSRF-protected API?

Should I check every time if the CSRF Cookie is set in the browser before sending any request?


Solution

  • You can do something like this. This is a dummy script.

    checkIfAuthenticated()
    .then( token => {
      // user is authorized. use token
    })
    .catch( err => {
      // oops. not authorized probably. authenticate user here.
    });
    
    // and your checkifAuthenticated:
    
    function checkifAuthenticated() {
      return new Promise((resovle, reject) => {
        // perform a http request here to /api?checkauth
        if(api_returned_401) {
          reject('not authenticated');
        } else {
          resolve(tokenOrInfo);
        }
      });
    }