Override the protect_from_forgery strategy in a controller

前端 未结 3 839
自闭症患者
自闭症患者 2021-02-06 13:21

I want to build a rails app with two different protect_from_forgery strategies: one for the web application, and one for the API.

In my application controller I have thi

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 14:18

    I am running an application with a similar structure - Web App + API. I solved the CSRF problem like this:

    • Apply protect_from_forgery only for non API requests
    • My API endpoint is api.example.com, so I used subdomain constraint to distinguish API and web app requests

    Code:

    class ApplicationController < ActionController::Base
    
      protect_from_forgery with: :exception, if: :isWebRequest?
    
      def isWebRequest?
        request.subdomains[-1] != 'api'
      end
    
    end
    

提交回复
热议问题