Decoding the Session Cookie: Rails 4.2

Posted: January 12, 2016. Tags: Rails

Here's how to view the contents of your Rails cookie, updated for Rails 4.2. You now must give MessageEncryptor a serializer: NullSerializer option or it tries to deserialize using Marshal and dies.

cookie = "cookie-string-copied-from-browser--with_signature"
cookie = CGI.unescape cookie
config = Rails.application.config
secrets = Rails.application.secrets

encrypted_cookie_salt = config.action_dispatch.encrypted_cookie_salt               # "encrypted cookie" by default
encrypted_signed_cookie_salt = config.action_dispatch.encrypted_signed_cookie_salt # "signed encrypted cookie" by default

key_generator = secrets.secret_key_base, iterations: 1000
secret = key_generator.generate_key encrypted_cookie_salt
sign_secret = key_generator.generate_key encrypted_signed_cookie_salt

encryptor = secret, sign_secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer
encryptor.decrypt_and_verify cookie

A word of caution about coping cookies our of browsers: If you're coping your cookie out of the Google Chrome Resources -> Cookies page, make sure you triple-click the cookie value before copying it (right-click and select Copy or Cmd-C on Mac OS X). If you just right click it and select Copy, it will only select the first "word" and you'll miss some necessary junk at the end of the cookie. Safari's Resources -> Cookies page has a "Copy Row" that is immune to this problem.