Question: Sails JS CSRF Token is different every call


Sails JS CSRF Token is different every call

Answers 1
Added at 2016-12-19 02:12

I want to enable CSRF in my SailsJS and Angular 2 application but I have been having endless problems.

The Angular app is on a page that is only accessible after a user has logged in, controlled by Sails policies. Then I http.get the CSRF token from the /csrfToken route and store it, adding it to HTTP headers when doing a POST.

I was continually getting CSRF mismatch errors and I finally realised that the /csrfToken route was returning a different value every time, both from a http.get and also when accessing the URL from the browser.

It wasn't clear that this was happening when I went through this tutorial (see 00:30) for a multi-page application where the CSRF value is submitted as a hidden field in a form, and there doesn't seem to be any mention of how to change this behaviour in the Sails documentation.

How can I configure Sails so that it will maintain a single CSRF value for a session?

UPDATE: It’s working now

I have made my update an answer as advised.

Answers to

Sails JS CSRF Token is different every call

nr: #1 dodano: 2016-12-22 01:12

It turns out that there were different issues that were causing my problems.

My code had become so fragmented that I didn’t realise I was referencing an older function that was putting the CSRF into the header wrong.

I rolled back a bunch of client-side code and then magically the CSRF value remained consistent between Ajax calls and also worked correctly in the POST request.

So I guess there was something in my fragmented code that had caused the CSRF token to change between API calls but I don’t know what it was.

Visiting /csrfToken in the browser still produces a different result every time but it does not seem to affect the API calls.


I discovered that the CSRF changes with each request to /csrfToken. One of my mistakes was that after I stored the CSRF value the first time I then (accidentally) requested a new /csrfToken again later, which then invalidated the stored value. Using the stored value would then result in a CSRF mismatch error as a new value had been issued.

Source Show
◀ Wstecz