Rails Login Reset Session

后端 未结 4 1242
难免孤独
难免孤独 2021-02-02 13:00

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?

4条回答
  •  清歌不尽
    2021-02-02 13:47

    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])
        temp_session = session.dup
        reset_session
        session.replace(temp_session)
        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.

提交回复
热议问题