禁用CSRF SiteWide [英] Disable CSRF SiteWide

查看:79
本文介绍了禁用CSRF SiteWide的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对所有控制器禁用CSRF,还是必须针对每个控制器禁用CSRF?我仅将ruby on rails用作API,并且不需要任何CSRF,因为请求几乎不是基于会话的。我只想禁用JSON请求。

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


推荐答案

与Rails中的许多功能一样,在基本控制器中禁用某些功能会在所有从其衍生的功能中禁用它。要完全关闭CSRF,请在ApplicationController中将其禁用:

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

这是一个的别名:

skip_before_action :verify_authenticity_token

skip_before_action 方法确实具有可自定义其应用方式的选项,因此您可以缩小对此的关注范围:

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?

如上所示,您可以定义限制它的方法。如果该方法返回 true ,该操作将照常执行,否则将被跳过。

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.

编写API时很常见具有类似于API :: BaseController之类的中间控制器,因此您可以将基于会话的活动与基于API的活动分开。例如:

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

然后派生所有特定于API的控制器从那一个。即使在主要由API驱动的应用程序中,您可能也需要一个带有表单提交的常规注册页面,或者一个具有编辑和更新功能的管理区域。

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.

我发现的一个选项是,如果提供了API密钥,则禁用CSRF保护。例如:

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

这意味着您仍然可以接受传统的形式编码或XML API调用。如果您的API密钥是通过标头提供的(如某些要求),则可以对其进行调整以相应地针对请求进行测试。

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.

这篇关于禁用CSRF SiteWide的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆