Reputation: 303
Hello I'm trying to encrypt and secure the data contained in my cookies but It seems like the data only gets encoded (base64)
This is an example:
cookies.signed[:example] = { :value => 'can you see this?', :httponly => true, :expire_after => 30.minutes, :secure => true }
And this is the content of the cookie:
BAhJIhZjYW4geW91IHNlZSB0aGlzPwY6BkVG--b4a8bbd7cd35e392ccd788df0008fd10b48442b2
And if I decode the string (base64) I get:
I"can you see this?:EFom{q{vq{_M<}to8f
I would like to know what I'm missing, currently this is what I have in
session_store.rb:
Service::Application.config.session_store :cookie_store, key: '_service_session'
And in my secret_token.rb I have set something like this:
Service::Application.config.secret_key_base = 'e892d55cbc205bb6..'
Upvotes: 1
Views: 910
Reputation: 5178
To piggy-back off of the accepted answer:
Depending on your situation: you might want to consider using a session cookie if you desire encryption. (As the accepted answer suggests: you can encrypt cookies, but perhaps a session cookie is more appropriate).
In rails 4 by default: the session cookie is by default encrypted and signed.
Specific section:
If you only have secret_token set, your cookies will be signed, but not encrypted. This means a user cannot alter their user_id without knowing your app's secret key, but can easily read their user_id. This was the default for Rails 3 apps.
If you have secret_key_base set, your cookies will be encrypted. This goes a step further than signed cookies in that encrypted cookies cannot be altered or read by users. This is the default starting in Rails 4.
secret_key_base
is located in rails 4 by default in: config/secrets.yml.
usage in rails 4:
# In rails 4 by default, this will be encrypted and signed
session[user_id] = 1
Upvotes: 1
Reputation: 4603
Your cookis is not encrypted, because you used the signed
method on the cookie jar, which, well, just signes the cookie content.
To encrypt the cookie, use the encrypted
method:
cookies.encrypted[:discount] = 45
# => Set-Cookie: discount=ZS9ZZ1R4cG1pcUJ1bm80anhQang3dz09LS1mbDZDSU5scGdOT3ltQ2dTdlhSdWpRPT0%3D--ab54663c9f4e3bc340c790d6d2b71e92f5b60315; path=/
cookies.encrypted[:discount] # => 45
Upvotes: 3