跳到內容 跳到搜尋
方法
P
S

執行個體公開方法

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
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 197
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,了解允許的選項。

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 214
def skip_forgery_protection(options = {})
  skip_before_action :verify_authenticity_token, options.reverse_merge(raise: false)
end