Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Login Reset Session

Is it best practice to call reset_session when a user successfully signs in and to call it again when a user signs out? Are there any side effects/problems to doing this?

like image 253
CalebHC Avatar asked Jan 27 '11 04:01

CalebHC


People also ask

What does Reset_session do in Rails?

Reset session will drop everything from the user's session, so if they hop back into the login screen and sign back in but still had (for example) a shopping cart stored to their session, you'll clear that which may be undesirable.

How do I delete a session in rails?

To clear the whole thing use the reset_session method in a controller. Resets the session by clearing out all the objects stored within and initializing a new session object.


1 Answers

The Ruby on Rails Security Guide recommends resetting the session id upon successful authentication to protect against session fixation vulnerabilities. Essentially, session fixation involves an attacker setting your session id (or some other method of being able to know what the id is when you hit the login page), and, upon your successful authentication, the attacker sets a cookie for their own browser using your session id and are subsequently authenticated as you. Resetting the session id upon successful authentication completely mitigates such a vulnerability. Some sample code in your create action might look like:

def create
  user =  User.find_by_email(params[:email])
  if user && user.authenticate(params[:password])
    old_values = session.to_hash
    reset_session
    session.update old_values.except('session_id')
    session[:athlete_id] = athlete.id
    redirect_to root_url, notice: "Authentication successful!"
  else
    flash.now.alert = "Invalid credentials"
    render "new"
  end
end

Note that it's important to duplicate the session before resetting it if there is any data you wish to preserve.

As far as calling reset_session on logout, yes, this is also best practice as well.

like image 161
rbhitchcock Avatar answered Oct 05 '22 18:10

rbhitchcock