Single Page Application and CSRF Token

前端 未结 4 690
礼貌的吻别
礼貌的吻别 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:20

    If you go with SPA application then you mostly use your Rails only as an API. CSRF token was designed for server rendering... not SPA. In SPA you already use token during authentication, so no need to use another token for CSRF. CSRF was designed as a protection for cross site calls, but API itself designed in a way that it allows request from anywhere until, they are authenticated.

    Just disable it for your API and that's all. I would go with some API namespace and setup a BaseController, that will be inherited for all API controllers. There you should set protect_from_forgery:

    class API::BaseController < ApplicationController
      protect_from_forgery with: :null_session
    end
    

提交回复
热议问题