跳至内容 跳至搜索

通过 ActionController::Cookies#cookies 读取和写入 cookie 数据。

读取 cookie 数据时,数据从 HTTP 请求头 Cookie 中读取。写入 cookie 数据时,数据在 HTTP 响应头 Set-Cookie 中发送。

写入示例

# Sets a simple session cookie.
# This cookie will be deleted when the user's browser is closed.
cookies[:user_name] = "david"

# Cookie values are String-based. Other data types need to be serialized.
cookies[:lat_lon] = JSON.generate([47.68, -122.37])

# Sets a cookie that expires in 1 hour.
cookies[:login] = { value: "XJ-122", expires: 1.hour }

# Sets a cookie that expires at a specific time.
cookies[:login] = { value: "XJ-122", expires: Time.utc(2020, 10, 15, 5) }

# Sets a signed cookie, which prevents users from tampering with its value.
cookies.signed[:user_id] = current_user.id
# It can be read using the signed method.
cookies.signed[:user_id] # => 123

# Sets an encrypted cookie value before sending it to the client which
# prevent users from reading and tampering with its value.
cookies.encrypted[:discount] = 45
# It can be read using the encrypted method.
cookies.encrypted[:discount] # => 45

# Sets a "permanent" cookie (which expires in 20 years from now).
cookies.permanent[:login] = "XJ-122"

# You can also chain these methods:
cookies.signed.permanent[:login] = "XJ-122"

读取示例

cookies[:user_name]           # => "david"
cookies.size                  # => 2
JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37]
cookies.signed[:login]        # => "XJ-122"
cookies.encrypted[:discount]  # => 45

删除示例

cookies.delete :user_name

请注意,如果您在设置 cookie 时指定了 :domain,则在删除 cookie 时也必须指定域。

cookies[:name] = {
  value: 'a yummy cookie',
  expires: 1.year,
  domain: 'domain.com'
}

cookies.delete(:name, domain: 'domain.com')

设置 cookie 的选项符号为

  • :value - cookie 的值。

  • :path - 此 cookie 适用的路径。默认为应用程序的根目录。

  • :domain - 此 cookie 适用的域,因此您可以限制到域级别。如果您使用类似 www.example.com 的模式,并且希望与 user.example.com 共享会话,请将 :domain 设置为 :all。要支持多个域,请提供一个数组,并且第一个与 request.host 匹配的域将被使用。确保在删除 cookie 时再次使用 :allArray 指定 :domain 选项。为了更灵活,您可以通过使用 proc 指定 :domain 来在每个请求的基础上设置域。

    domain: nil  # Does not set cookie domain. (default)
    domain: :all # Allow the cookie for the top most level
                 # domain and subdomains.
    domain: %w(.example.com .example.org) # Allow the cookie
                                          # for concrete domain names.
    domain: proc { Tenant.current.cookie_domain } # Set cookie domain dynamically
    domain: proc { |req| ".sub.#{req.host}" }     # Set cookie domain dynamically based on request
    
  • :tld_length - 使用 :domain => :all 时,此选项可用于在使用被解释为 TLD 部分的短(<= 3 个字符)域时显式设置 TLD 长度。例如,要在 user1.lvh.me 和 user2.lvh.me 之间共享 cookie,请将 :tld_length 设置为 2。

  • :expires - 此 cookie 过期的時間,以 TimeActiveSupport::Duration 对象表示。

  • :secure - 此 cookie 是否只传输到 HTTPS 服务器。默认为 false

  • :httponly - 此 cookie 是否可通过脚本访问,或者仅通过 HTTP 访问。默认为 false

  • :same_site - SameSite cookie 属性的值,它决定了此 cookie 在跨站点上下文中如何限制。可能的值为 nil:none:lax:strict。默认为 :lax

命名空间
方法
C
N

常量

AUTHENTICATED_ENCRYPTED_COOKIE_SALT = "action_dispatch.authenticated_encrypted_cookie_salt"
 
COOKIES_DIGEST = "action_dispatch.cookies_digest"
 
COOKIES_ROTATIONS = "action_dispatch.cookies_rotations"
 
COOKIES_SAME_SITE_PROTECTION = "action_dispatch.cookies_same_site_protection"
 
COOKIES_SERIALIZER = "action_dispatch.cookies_serializer"
 
CookieOverflow = Class.new StandardError
 

当存储超过 4K 的会话数据时引发。

ENCRYPTED_COOKIE_CIPHER = "action_dispatch.encrypted_cookie_cipher"
 
ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt"
 
ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt"
 
GENERATOR_KEY = "action_dispatch.key_generator"
 
HTTP_HEADER = "Set-Cookie"
 
MAX_COOKIE_SIZE = 4096
 

Cookies 通常可以存储 4096 字节。

SECRET_KEY_BASE = "action_dispatch.secret_key_base"
 
SIGNED_COOKIE_DIGEST = "action_dispatch.signed_cookie_digest"
 
SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt"
 
USE_AUTHENTICATED_COOKIE_ENCRYPTION = "action_dispatch.use_authenticated_cookie_encryption"
 
USE_COOKIES_WITH_METADATA = "action_dispatch.use_cookies_with_metadata"
 

类公共方法

new(app)

# File actionpack/lib/action_dispatch/middleware/cookies.rb, line 700
def initialize(app)
  @app = app
end

实例公共方法

call(env)

# File actionpack/lib/action_dispatch/middleware/cookies.rb, line 704
def call(env)
  request = ActionDispatch::Request.new(env)
  response = @app.call(env)

  if request.have_cookie_jar?
    cookie_jar = request.cookie_jar
    unless cookie_jar.committed?
      response = Rack::Response[*response]
      cookie_jar.write(response)
    end
  end

  response.to_a
end