实例公共方法
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 与 Cookie 身份验证))时,这非常有用。如果您需要在回调链的开头添加验证,请使用
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 179 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 196 def skip_forgery_protection(options = {}) skip_before_action :verify_authenticity_token, options.reverse_merge(raise: false) end