Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
Weihang Jian Avatar asked Dec 02 '16 19:12

Weihang Jian


2 Answers

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?

like image 200
georgebrock Avatar answered Oct 17 '22 08:10

georgebrock


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.

like image 3
Masong Avatar answered Oct 17 '22 10:10

Masong