Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure session cookies for rails application

I have the following configuration in my session_store.rb

Fuel::Application.config.session_store :cookie_store,
  :key => "_secure_session",
  :secure => !(Rails.env.development? || Rails.env.test?),
  :domain => :all

In application_controller.rb

def default_url_options
  return { :only_path => false, :port => 443, :protocol => 'https' }
end

I am using devise and my rails3 server is running behind HAProxy. HAProxy terminates the HTTPS traffic and passes HTTP requests to Rails. My problem is when i turn on :secure => true in session_store.rb, the user is redirected back to the sign in page with the message "Unauthorized". I have tried debugging it a lot, not sure how to get it working.

Its a situation where HAProxy is the reverse proxy terminating all the secure traffic and passing non-secure traffic to rails. When rails sets the cookie to secure, somehow it itself is not able to access it.

like image 946
Pratik Khadloya Avatar asked Feb 18 '23 06:02

Pratik Khadloya


2 Answers

For your normal session cookie, your doing this correctly. You should see the '_secure_session' cookie properly set as secure in your browser. For the Devise "remember me" cookie you'll need to set that in the devise config. In config/initializers/devise.rb you'll find a line somewhere around line 133 that looks like

# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.cookie_options = {}

I changed that to:

config.rememberable_options = {:secure => Rails.env.production?}
like image 147
Joe Basirico Avatar answered Feb 23 '23 07:02

Joe Basirico


If Set-cookie is not being sent to the browser on initial authentication, then it sounds like a devise problem.

If Set-cookie is going to the browser, but not being sent back on the next https:// request, then it's probably a mismatch on :secure => setting.

If the cookie is sent by the browser, but not passed along by HAProxy, then it's a HAProxy configuration problem.

If the cookie is in the ruby environment, and being ignored due to policy, then it's a problem somewhere in Ruby code - at a guess, around secure/not-secure cookie-matching.

like image 25
user1760826 Avatar answered Feb 23 '23 07:02

user1760826