In a Rails controller, how do cookies.signed and cookies.encrypted differ, and which fits a remember-me token versus a dismissed-banner flag?
answer
- tamper-proof versus also unreadable
- base64 data, two dashes, digest
- AES-256-GCM keyed from secret_key_base
- a bad value reads as nil
- plain cookies come back as strings
basics
~20 scookies.signed adds an HMAC so the client can read but not change the value; cookies.encrypted also hides it with AES-256-GCM. Both return nil for a tampered value. A remember-me token goes in a signed or encrypted jar; a dismissed-banner flag can be a plain cookie.
solid answer
~40 sBoth jars derive keys from `secret_key_base` through Rails' key generator. `cookies.signed[:remember_token] = token` writes Base64 data, `--` and an HMAC digest: anyone can decode the data, nobody can change it without the key, and a modified value reads back as `nil`. `cookies.encrypted[...]` encrypts and authenticates with AES-256-GCM, so the value is neither readable nor changeable. Both serialize the value (JSON under the 7.0+ defaults), so an Integer comes back as an Integer, while a plain `cookies[:banner_dismissed] = true` comes back as the string `"true"`. Pick signed for a random token the server looks up, encrypted when the value itself must stay private, and a plain cookie for a harmless UI flag. Always read through the same jar you wrote with.
code
ruby · 13 linesclass RememberedLoginsController < ApplicationController
def create
token = SecureRandom.urlsafe_base64(32)
RememberToken.create!(reader: Current.reader, token_digest: Digest::SHA256.hexdigest(token))
cookies.signed[:remember_token] = {
value: token, expires: 2.weeks, httponly: true, secure: Rails.env.production?
}
head :no_content
end
end
# app/controllers/banners_controller.rb
cookies[:banner_dismissed] = { value: "1", expires: 1.year }go deeper
Recall that signed cookies cannot be changed undetected, encrypted cookies cannot be read or changed, and both are read back through the same jar.
Explain the Base64--digest format, AES-256-GCM, nil on failure, the JSON serializer's effect on types, and why a plain cookie returns strings.
Show you pick the jar from the data's sensitivity, pair it with httponly, secure and an expiry, and plan for secret changes with cookies_rotations.
Decide what the app may keep client-side at all, and keep authorizing state server-side so a leaked or replayed cookie can be revoked.
## Three ways to write a cookie A news-reader app sets two cookies: a **remember-me token** that keeps a reader signed in, and a **dismissed-banner flag** that hides the newsletter banner. Rails' `cookies` object offers three jars for them: ```ruby cookies[:banner_dismissed] = { value: "1", expires: 1.year } # plain cookies.signed[:remember_token] = { value: token, expires: 2.weeks } # signed cookies.encrypted[:reader_prefs] = { value: { font: "serif" } } # encrypted ``` Reading must go through the **same jar**: `cookies.signed[:remember_token]` returns the verified value, while `cookies[:remember_token]` returns the raw signed string. ## What each jar does to the value | Jar | Client can read | Client can change undetected | Value type on read | |---|---|---|---| | `cookies[...]` | yes | yes | String | | `cookies.signed[...]` | yes, it is Base64 | no, `nil` on mismatch | as serialized | | `cookies.encrypted[...]` | no | no, `nil` on failure | as serialized | - **Signed.** Rails serializes the value, Base64-encodes it, and appends `--` and an HMAC digest computed with a key derived from `secret_key_base` and the salt `config.action_dispatch.signed_cookie_salt`. Decoding the first part needs no key, so a signed cookie is **not secret**. - **Encrypted.** Rails serializes the value and encrypts it with **AES-256-GCM** (the 5.2 defaults and later), which also authenticates it. The key comes from `secret_key_base` and the authenticated-encryption salt. - **Plain.** The value is sent as given. Cookie values are strings, so `cookies[:banner_dismissed] = true` reads back as `"true"` on the next request. For both signed and encrypted jars, a value that fails verification or decryption reads as **`nil`**, not an exception, so code treats it like a missing cookie. ## Serialization and types The signed and encrypted jars run the value through `config.action_dispatch.cookies_serializer`, which is `:json` under `load_defaults` 7.0 and later. An Integer comes back as an Integer and `false` as `false`, but a Symbol comes back as a String and a hash's symbol keys as string keys. Plain cookies skip the serializer; store JSON yourself if you need structure. ## Choosing for the two cookies 1. **Remember-me token.** The usual design stores a long random token, keeps its digest in the database, and looks it up on each visit. The token is meaningless without the database, so **signed** is enough: it stops a reader swapping in someone else's token by editing the cookie. Use **encrypted** if the cookie would carry something you do not want visible, such as a user id plus metadata. 2. **Dismissed-banner flag.** If a reader edits it, the worst outcome is seeing a banner. A **plain** cookie is fine, and it stays readable for debugging. 3. **Never** put a password, an API key or anything authorizing by itself in a plain or signed cookie. ## Size limits differ by jar The signed and encrypted jars check the result: if the cookie's name plus its final, encoded value exceeds 4096 bytes, they raise `ActionDispatch::Cookies::CookieOverflow`. Signing adds a digest and encryption adds a nonce and tag before Base64 encoding, so the usable payload is well below that. The plain jar performs **no** such check; an oversized plain cookie is sent as is and the browser may drop it. Either way, keep cookie values to a token or a flag, never a whole profile. ## Attributes still matter The jar protects the **value**; the attributes decide where the cookie travels. For a remember-me token pass `httponly: true` so page scripts cannot read it, `secure: true` (or rely on `config.force_ssl`) so it never crosses plain HTTP, and an explicit `expires:` so it ends. Rails' defaults are `path: "/"`, the configured `SameSite` (`:lax` under the 6.1 defaults and later) and no `HttpOnly`. ## What breaks when secret_key_base changes Every signed and encrypted cookie, the session cookie included, stops verifying and reads as `nil`, so readers are signed out and lose encrypted preferences. Plain cookies are unaffected. `config.action_dispatch.cookies_rotations` lets Rails accept cookies made with an old secret while writing new ones with the current secret.
- What does cookies[:remember_token] return when the cookie was written with cookies.signed?The raw signed string: Base64 data, `--` and the digest. Only `cookies.signed[:remember_token]` verifies the digest and returns the original value, or `nil` if it was altered. Reading through the wrong jar is a common reason a remember-me check never matches.
- Why does cookies.signed[:count] = 3 read back as 3 while cookies[:count] = 3 reads back as "3"?The signed and encrypted jars serialize the value (JSON under the 7.0+ defaults), so its type survives the round trip. A plain cookie sends the value as text, so the next request sees the string `"3"`.
- a signed cookie hides its value from the user as well as protecting it
- a tampered encrypted cookie raises an exception when it is read
- cookies[:name] returns the verified value of a signed cookie
- a plain cookie set to true reads back as the boolean true
- the encrypted jar makes HttpOnly and Secure unnecessary