Single Page Application and CSRF Token

前端 未结 4 687
礼貌的吻别
礼貌的吻别 2020-12-01 19:54

I need to use a Single Page Application (React, Ember, Angular, I don\'t care) with Rails CSRF protection mechanism.

I\'m wondering if I need to create a token evey

4条回答
  •  死守一世寂寞
    2020-12-01 20:27

    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.

提交回复
热议问题