Is there a way to disable CSRF for all controllers, or does it have to be disabled on a per-controller basis? I am using ruby on rails as an API only and do not need any sort of CSRF as the requests aren't anywhere near session based. I'd like to disable just for JSON requests.
I believe this might work, but am unsure
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
#Checks format for json
protected
def json_request?
request.format.json?
end
end
As with many things in Rails, disabling something in a base controller has the effect of disabling it in all those derived from it. To turn off CSRF completely, disable it in ApplicationController:
skip_before_action :verify_authenticity_token
The skip_before_action
method does have options to customize how it's applied, so you can narrow down the focus on this:
skip_before_action :verify_authenticity_token, unless: csrf_required?
Where as you've shown you can define a method to restrict it. If that method returns true
the action is executed as usual, otherwise it's skipped.
When writing an API it's common to have something like API::BaseController as an intermediate controller so you can separate session-based activity from API-based activity. For example:
class API::BaseController < ApplicationController
skip_before_action :verify_authenticity_token
end
Then derive all your API-specific controllers from that one. Even in an application that's predominantly API driven, you may need a conventional "signup" page with a form submission on it, or an admin area with the ability to edit and update things.
One option I've discovered is to disable CSRF protection if an API key is supplied. For example:
def csrf_required?
params[:api_key].blank?
end
That means you can still accept traditional "form-encoded" or XML API calls. If your API key is supplied via headers instead, as some require, you can adapt that to test against request
accordingly.
来源:https://stackoverflow.com/questions/26388243/disable-csrf-sitewide