Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sessions made sense to me before I started reading about them online

The main thing I've gathered from reading about Sessions vs Cookies is that Cookies are stored on the client-side and that sessions are stored on the server-side. If sessions are stored on the server-side, then how does the server ever know which client is theirs? Clearly, something must be on the client-side.

Whenever I use my self-rolled user authentication, I have a session_token column in my users database table.

Then, this module tends to facilitate sessions for me:

module SessionsHelper
  def current_user
    User.find_by_session_token(session[:session_token])
  end

  def current_user=(user)
    @current_user = user
    session[:session_token] = user.session_token
  end

  def logout_current_user!
    current_user.reset_session_token!
    session[:session_token] = nil
  end

  def require_current_user!
    redirect_to new_session_url if current_user.nil?
  end

  def require_no_current_user!
    redirect_to user_url(current_user) unless current_user.nil?
  end
end

I believe by sessions being stored on the server-side, they mean the session_token every User has. Further, the session hash must be on the client-side. If not, where is it? Notice, I'm storing the session_token of the user like this: session[:session_token] = user.session_token. Lastly, if I'm right that the session is on the client-side, how are it and the session_token kept secure?

Lastly, is this the same way sessions tend to be handled on other frameworks (like Django, php frameworks, etc.)? If not, what are some key differences?

Many thanks.

like image 842
David Avatar asked Jan 31 '14 22:01

David


1 Answers

The Rails security guide has some good information on sessions:

http://guides.rubyonrails.org/v3.2.16/security.html#sessions

Basically, the session data can all be stored in the cookie (the default) but it's signed with a digest to protect against tampering using a server-side secret (but the cookie data is not encrypted in Rails 3.2, only base64 encoded, though I believe it is encrypted in Rails 4).

The alternative is that only the session id is stored in the cookie, and the session data is stored on the server somewhere (e.g. ActiveRecord::SessionStore).

I think the client/server side session options would be widely supported (especially server-side). Other options for server-side session storage could be memcache shared between servers, or even memory or file storage which would be separate for each web server in a cluster which would mean your load balancer would need to support sticky sessions (to make sure a user's requests were all routed to the same server because the other servers wouldn't know about it). If I remember correctly, that's what Apache Tomcat was like in the old days for server-side sessions, before clustering support was added.

like image 53
Tim Avatar answered Sep 18 '22 07:09

Tim