略過至內容 略過至搜尋

透過 ActionController::Cookies#cookies 讀取及寫入資料到 Cookies 中。

在讀取 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 時,可以使用這個選項在使用短 (<= 3 個字元) 網域,並將其解譯為 TLD 一部分時,明確設定 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"
 
加密簽署 COOKIE 雜湊鹽 = "action_dispatch.encrypted_signed_cookie_salt"
 
產生器金鑰 = "action_dispatch.key_generator"
 
HTTP 標頭 = "Set-Cookie"
 
最大的 COOKIE 尺寸 = 4096
 

Cookie 通常可以儲存 4096 位元組。

秘密金鑰基礎 = "action_dispatch.secret_key_base"
 
已簽署的 COOKIE 摘要 = "action_dispatch.signed_cookie_digest"
 
已簽署的 COOKIE 雜湊鹽 = "action_dispatch.signed_cookie_salt"
 
使用經過認證的 COOKIE 加密 = "action_dispatch.use_authenticated_cookie_encryption"
 
使用有資料的 COOKIE = "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