跳至内容 跳至搜索

包含在 Cookie Jar 中以允许链式调用,例如 cookies.permanent.signed

方法
E
P
S

实例公共方法

encrypted()

返回一个 Jar,该 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,该 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 仅用于写入。您将通过常规访问器读取永久 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,该 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 Store。

# 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