Single Page Application and CSRF Token

Client side (SPA)

You only need to grab the CSRF token once per session. You can hold onto it in the browser and send it on every (non-GET) request.

Rails will appear to generate a new CSRF token on every request, but it will accept any generated token from that session. In reality, it is just masking a single token using a one-time pad per request, in order to protect against SSL BREACH attack. More details at https://stackoverflow.com/a/49783739/2016618. You don’t need to track/store these tokens.

Server side

I strongly suggest using Rails’s protect_from_forgery directive rather than encoding the CSRF token in a header yourself. It will generate a different masked token per request.

You can certainly reproduce this yourself with not that much code, but I don’t see why you’d need to.

Do you need CSRF protection with an API?

Yes! If you are authenticating with a cookie, you need CSRF protection. This is because cookies are sent with every request, so a malicious website could send a POST request to your site and perform requests on behalf of a logged in user. The CSRF token prevents this, because the malicious site won’t know the CSRF token.

Leave a Comment