Skip to content

Instantly share code, notes, and snippets.

@tadast
Forked from mbyczkowski/with_active_support.rb
Last active December 10, 2018 11:41
Show Gist options
  • Save tadast/769541b7fb82b31466dc620af40fe362 to your computer and use it in GitHub Desktop.
Save tadast/769541b7fb82b31466dc620af40fe362 to your computer and use it in GitHub Desktop.
session cookie decrypter for Rails 5.1
require 'cgi'
require 'json'
require 'active_support'
def verify_and_decrypt_session_cookie(cookie, secret_key_base = Rails.application.secrets.secret_key_base)
cookie = CGI::unescape(cookie)
salt = 'encrypted cookie'
signed_salt = 'signed encrypted cookie'
key_generator = ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)
secret = key_generator.generate_key(salt)[0, ActiveSupport::MessageEncryptor.key_len]
sign_secret = key_generator.generate_key(signed_salt)
encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
encryptor.decrypt_and_verify(cookie)
end
# Usage:
# cookie = "< the value on the right of `_server_session=<this>`"
# verify_and_decrypt_session_cookie(cookie)
@9mm
Copy link

9mm commented Jul 1, 2018

How do you handle Rails.application.secrets.secret_key_base being nil in development? (for new rails 5.2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment