Override the protect_from_forgery strategy in a controller

前端 未结 3 836
自闭症患者
自闭症患者 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:03

    What if you leave the protect_from_forgery with: :exception in the application controller but then you put the following in your API controller?

    skip_before_action :protect_from_forgery
    protect_from_forgery with: :null_session
    

    That way, you still get the standard CSRF attack protection for all controllers in your web application but you also get the null session behavior for your API methods.

    0 讨论(0)
  • 2021-02-06 14:03

    Late to the party, but something like this can be done:

    class YourCustomStrategy
      def initialize(controller)
      end
    
      def handle_request
      end
    end
    

    And in your ApplicationController or where you want:

    class ApplicationController < ActionController::Base
     protect_from_forgery with: YourCustomStrategy
    end
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题