Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set session cookie as secure in rails

I have Rails application, which is running on https. My application session cookies are http-only. How to set those cookies as secure and https-only in rails?

like image 402
Srinivas Yadav Avatar asked Mar 19 '15 11:03

Srinivas Yadav


People also ask

How do I mark session cookies as secure?

Mark cookies as Secure Response. Cookies. Add( new HttpCookie("key", "value") { Secure = true, }); That's it!

Are cookie based sessions secure?

The cookie allows the server to identify the user and retrieve the user session from the session database, so that the user session is maintained. A cookie-based session ends when the user logs off or closes the browser. Cookie-based session management is secure and has performance benefits over alternatives.

What is the difference between a cookie with the secure flag set?

The Secure flag is used to declare that the cookie may only be transmitted using a secure connection (SSL/HTTPS). If this cookie is set, the browser will never send the cookie if the connection is HTTP. This flag prevents cookie theft via man-in-the-middle attacks.

What is session and cookies in Rails?

Cookies, Sessions and Flashes are three special objects that Rails gives you in which each behave a lot like hashes. They are used to persist data between requests, whether until just the next request, until the browser is closed, or until a specified expiration has been reached.


Video Answer


1 Answers

Rails 3/4

If you want to flag the session cookie as secure, in config/initializers/session_store.rb, set the secure flag:

Demo::Application.config.session_store :cookie_store,
  key: '_demo_session',
  secret: "your secret",
  secure: Rails.env.production?, # flags cookies as secure only in production
  httponly: true # should be true by default for all cookies

If you want to flag all cookies as secure, add config.force_ssl = true in the desired config/environments/*.rb file. This feature adds other functionality to your Rails app, summarized here.

like image 200
jmera Avatar answered Oct 16 '22 07:10

jmera