Weihang Jian
Weihang Jian

Reputation: 8715

Why Rails change Set-Cookie header every request for the same session

I'm using Rails 4 with cookie based session store, found that Rails 4 will give me a different cookie every time I refresh the page, but it can still identify me.

Compare it to another rack app which uses Rack::Session::Cookie, it will only send Set-Cookie for the first request, until some changes to session data were made.

Why are they designed differently? Is there any reason behind?

Upvotes: 7

Views: 3894

Answers (2)

Masong
Masong

Reputation: 31

Rails cookie_store default use the EncryptedKeyRotatingCookieJar, and generate the encrypt_and_sign value. That value use MessageEncryptor#_encrypt method, which use the Random 【cipher.random_iv】. So, every time the same value will generate a different encrypt_and_sign result.

Upvotes: 3

georgebrock
georgebrock

Reputation: 30043

It's because of the way Rails handles session storage and cookie encryption:

  1. the default session store will try to write the session data to an encrypted cookie on any request that has accessed the session (either to read from it or write to it),
  2. the encrypted value changes even when the plain text value hasn't,
  3. the encryption happens before it reaches the code that's responsible for checking if a cookie value has changed to avoid redundant Set-Cookie headers.

I go into much more detail in answering this question: Why is rails constantly sending back a Set-Cookie header?

Upvotes: 4

Related Questions