Disable CSRF SiteWide

☆樱花仙子☆ 提交于 2019-12-05 14:31:31

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.

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