1

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?

alayor
  • 4,537
  • 6
  • 27
  • 47
  • You can create a custom endpoint something like /api?request=token which is not CSRF protected and returns the token only. Really depends how your API is programmed. – mehulmpt Aug 05 '17 at 14:13
  • Does this mean that I'd have to check every time if I have the cookie set in order to send this request? – alayor Aug 05 '17 at 14:31

1 Answers1

1

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);
    }
  });
}
mehulmpt
  • 15,861
  • 12
  • 48
  • 88