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_forgery_protection
This is an alias for:
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.