Rails 有关 API 请求的 RequestForgeryProtection 的文档

Rails documentation on RequestForgeryProtection for API requests

我正在阅读 protect_from_forgery http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html 上的笔记,这几行让我很困惑。

It's important to remember that XML or JSON requests are also affected and if you're building an API you should change forgery protection method in ApplicationController (by default: :exception):

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

CSRF protection is turned on with the protect_from_forgery method. By default protect_from_forgery protects your session with :null_session method, which provides an empty session during request.

它说异常是 protect_from_forgery unless: -> { request.format.json? } 的默认值,但后来说 null_session 是 protect_from_forgery 的默认值。

是否意味着如果我们使用protect_from_forgery unless: -> { request.format.json? },异常将成为默认值?如果我们使用 protect_from_forgery,null_session 将成为默认值?

非常感谢任何帮助。

文档是准确的,如果有点混乱;每个语句指的是不同的 "default" 行为。第一条语句的意思是,新 Rails 应用程序的默认设置是使用以下行生成您的 ApplicationController:

protect_from_forgery :exception

第二个语句的意思是,对于 protect_from_forgery 方法,如果省略参数,则默认值为 :null_session。因此,如果您要从 ApplicationController 中删除 :exception,即,您刚刚拥有:

protect_from_forgery

那么使用的行为将是 :null_session 的行为(参见 implementation 的证明)。

所以第一条语句是指为新 Rails 应用程序默认生成的代码;第二条语句引用方法本身的默认值。奇怪的是,它们是不同的。