跳至內容 跳至搜尋

將其包含在 Cookie Jar 中以允許鏈式操作,例如 cookies.permanent.signed

方法
E
P
S

實例公開方法

encrypted()

返回一個 Jar,它會在將 Cookie 值發送到客戶端之前自動加密,並在讀取時解密。如果 Cookie 被用戶(或第三方)篡改,將返回 nil

如果同時設定了 config.action_dispatch.encrypted_cookie_saltconfig.action_dispatch.encrypted_signed_cookie_salt,則使用 HMAC AES-256-CBC 加密的舊 Cookie 將被透明地升級。

這個 Jar 要求您在應用程式的 secret_key_base 中設定一個合適的驗證密鑰。

範例

cookies.encrypted[:discount] = 45
# => Set-Cookie: discount=DIQ7fw==--K3n//8vvnSbGq9dA--7Xh91HfLpwzbj1czhBiwOg==; path=/

cookies.encrypted[:discount] # => 45
# File actionpack/lib/action_dispatch/middleware/cookies.rb, line 274
def encrypted
  @encrypted ||= EncryptedKeyRotatingCookieJar.new(self)
end

permanent()

返回一個 Jar,它會自動將指定的 Cookie 設定為從現在起 20 年後過期。範例

cookies.permanent[:prefers_open_id] = true
# => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT

這個 Jar 僅用於寫入。您將通過常規 accessor 讀取永久性 Cookie。

這個 Jar 也允許與 signed jar 鏈式操作,因此您可以設定永久性、簽章的 Cookie。範例

cookies.permanent.signed[:remember_me] = current_user.id
# => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
# File actionpack/lib/action_dispatch/middleware/cookies.rb, line 234
def permanent
  @permanent ||= PermanentCookieJar.new(self)
end

signed()

返回一個 Jar,它會自動產生 Cookie 值的簽章表示形式,並在再次從 Cookie 讀取時驗證它。這對於建立具有用戶不應更改的值的 Cookie 很有用。如果簽章的 Cookie 被用戶(或第三方)篡改,將返回 nil

這個 Jar 要求您在應用程式的 secret_key_base 中設定一個合適的驗證密鑰。

範例

cookies.signed[:discount] = 45
# => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/

cookies.signed[:discount] # => 45
# File actionpack/lib/action_dispatch/middleware/cookies.rb, line 253
def signed
  @signed ||= SignedKeyRotatingCookieJar.new(self)
end

signed_or_encrypted()

返回 signedencrypted jar,如果設定了 secret_key_base,則優先使用 encrypted。由 ActionDispatch::Session::CookieStore 使用,以避免需要引入新的 Cookie 存放區。

# File actionpack/lib/action_dispatch/middleware/cookies.rb, line 281
def signed_or_encrypted
  @signed_or_encrypted ||=
    if request.secret_key_base.present?
      encrypted
    else
      signed
    end
end