Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make cookies secure (https-only) by default in rails?

In a Rails controller, I can set a cookie like this:

cookies[:foo] = "bar" 

And specify that the "secure" (https-only) flag be on like this:

cookies[:foo, :secure => true] = "bar" 

:secure is false by default. How can I have cookies be secure by default, application-wide?

This is on Rails 2.3.8

like image 614
John Bachir Avatar asked Sep 22 '10 21:09

John Bachir


People also ask

Are cookies secure by default?

In May, Chrome announced a secure-by-default model for cookies, enabled by a new cookie classification system (spec). This initiative is part of our ongoing effort to improve privacy and security across the web. Chrome plans to implement the new model with Chrome 80 in February 2020.

Can a cookie be HttpOnly and secure?

Security of cookies is an important subject. HttpOnly and secure flags can be used to make the cookies more secure. When a secure flag is used, then the cookie will only be sent over HTTPS, which is HTTP over SSL/TLS.


2 Answers

There's no need to monkeypatch ActionController/ActionDispatch, and force_ssl has side effects (e.g. when behind an ELB).

The most straightforward way to achieve secure cookies is to modify config/initializers/session_store.rb:

MyApp::Application.config.session_store(    :cookie_store,    key: '_my_app_session',   secure: Rails.env.production? ) 
like image 138
David Cain Avatar answered Sep 20 '22 17:09

David Cain


starting with rails 3.1, according to the rails security guide, you can simply set the following in your application.rb:

config.force_ssl = true 

this forces the cookie to be sent over https only (and I assume everything else, too).

like image 25
Markus Avatar answered Sep 20 '22 17:09

Markus