Reputation: 3090
I send an email address as signed cookie:
cookies.signed[:user_email] = { value: user.email, expires: 24.hours.from_now }
Later the frontend sends it back to me as an HTTP header:
request.headers["HTTP_USER_EMAIL"]
How to then decrypt from the received header to the original email address? I tried the line below, but it produces the error:
NoMethodError Exception: undefined method `signed' for #String:0x00000008a57a78
email = request.headers["HTTP_USER_EMAIL"].signed unless (request.headers["HTTP_USER_EMAIL"] == nil)
With debugger
I get a value for request.headers["HTTP_USER_EMAIL"]
of "Im9yZ29utcGxlLmNvbSI=--37ddc725d139f86095ae839012c31a14e"
. So the encrypted value is there.
Difference value in cookie versus header: If the encrypted value would be found in a cookie, you could decrypt it using cookies.signed[:http_user_email]
. My attempts of request.headers["HTTP_USER_EMAIL"].signed
and request.headers.signed["HTTP_USER_EMAIL"]
are basically the same as when with a cookie you would take the encrypted value of the cookie and add .signed at the end: "Im9yZ29utcGxlL".signed
. And that wouldn't work either. But how then to do it if the encrypted value is found in a string?
Or would you argue there's no need to use an encrypted version of the user's email address for API authentication? Authentication is done based on the combination of the email address and a token (the token needs to match the digest which is an encrypted version of the token).
Upvotes: 9
Views: 1013
Reputation: 8785
At config/initializers/secret_token.rb
you should have the password:
Demo::Application.config.secret_key_base = 'b14e9b5b720f84fe02307ed16bc1a32ce6f089e10f7948422ccf3349d8ab586869c11958c70f46ab4cfd51f0d41043b7b249a74df7d53c7375d50f187750a0f5'
To decrypt:
content = request.headers["HTTP_USER_EMAIL"]
unescaped_content = URI.unescape(content)
crypt = ActiveSupport::MessageEncryptor.new(Rails.configuration.secret_key_base)
data = crypt.decrypt_and_verify(unescaped_content)
In 4.0 based on default configuration. In 4.1 onwards you could have config/secrets.yml instead of secret_token.rb
Upvotes: 1
Reputation: 4316
set the value as cookie and access it with signed
so in your case
mail_signed = request.headers["HTTP_USER_EMAIL"]
cookies[:mail]=mail_signed
mail = cookies.signed[:mail]
Upvotes: 0