Override the protect_from_forgery strategy in a controller

放肆的年华 提交于 2019-12-03 03:40:36

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.

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!