实例公共方法
protect_from_forgery(options = {}) 链接
启用请求伪造保护。请注意,GET 和 HEAD 请求不会被检查。
class ApplicationController < ActionController::Base protect_from_forgery end class FooController < ApplicationController protect_from_forgery except: :index end
您可以使用 skip_forgery_protection 在控制器上禁用伪造保护。
class BarController < ApplicationController skip_forgery_protection end
有效选项
-
:only/:except- 仅将伪造保护应用于部分动作。例如only: [ :create, :create_all ]。 -
:if/:unless- 根据传递的 Proc 或方法引用,完全关闭伪造保护。 -
:prepend- 默认情况下,身份验证令牌的验证将在您的应用程序中protect_from_forgery调用的位置添加。这意味着任何之前添加的回调都会先运行。当您希望伪造保护依赖于其他回调(如身份验证方法(Oauth vs Cookie auth))时,这很有用。如果您需要将验证添加到回调链的开头,请使用
prepend: true。 -
:with- 设置处理未经验证请求的方法。请注意,如果default_protect_from_forgery为 true,Rails会以with :exception调用protect_from_forgery。
内置的未经验证请求处理方法有:
-
:exception- 引发 ActionController::InvalidAuthenticityToken 异常。 -
:reset_session- 重置会话。 -
:null_session- 在请求期间提供一个空会话,但不会完全重置它。如果未指定:with选项,则作为默认值使用。
您还可以为未经验证的请求处理实现自定义策略类。
class CustomStrategy def initialize(controller) @controller = controller end def handle_unverified_request # Custom behavior for unverfied request end end class ApplicationController < ActionController::Base protect_from_forgery with: CustomStrategy end
-
:store- 设置用于存储和检索 CSRF 令牌的策略。
内置会话令牌策略有:
-
:session- 将 CSRF 令牌存储在会话中。如果未指定:store选项,则作为默认值使用。 -
:cookie- 将 CSRF 令牌存储在加密的 cookie 中。
您还可以为 CSRF 令牌存储实现自定义策略类。
class CustomStore def fetch(request) # Return the token from a custom location end def store(request, csrf_token) # Store the token in a custom location end def reset(request) # Delete the stored session token end end class ApplicationController < ActionController::Base protect_from_forgery store: CustomStore.new end
来源: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 206 def protect_from_forgery(options = {}) options = options.reverse_merge(prepend: false) self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session) self.request_forgery_protection_token ||= :authenticity_token self.csrf_token_storage_strategy = storage_strategy(options[:store] || SessionStore.new) before_action :verify_authenticity_token, options append_after_action :verify_same_origin_request end
skip_forgery_protection(options = {}) 链接
关闭请求伪造保护。这是以下方法的包装器:
skip_before_action :verify_authenticity_token
有关允许的选项,请参阅 skip_before_action。
来源: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 223 def skip_forgery_protection(options = {}) skip_before_action :verify_authenticity_token, options.reverse_merge(raise: false) end