Session Not Destroyed When Closing Browser - Railstutorial.Org

In Rails, how do you destroy a session when a browser is closed?

EDIT:
Looking at the link you gave, they write:

We can also start the server (with “$ rails s”) and verify the
functioning of our brand new session without cookies (we should be
logged out every time we close the browser).

(emphasis added)

Therefore, their solution is to simply turn off cookies, which results in a new session being created with each visit. They are not really talking about removing old sessions on the server side of the equation.

My original answer is left below for historical value:


(apologies if this is too general, I'm assuming you're not seeing the bigger picture)

Fundamentally, the web uses a pull-based model - clients make requests to do things on the server.

You can not 'force' the client to close a session, since closing a session is an action that the client must request from the server (eg: by logging out).

Therefore, typically sessions have a time-out period that is checked regularly. Each session has a 'start time' stored in the database, and sessions that are too old are purged.

That said, there may be some way in javascript to detect a browser close event and make some best-effort attempt to close the session. But there is no guarantee - the user can always forcefully kill the browser process, leaving the server totally in the dark.

In short, you can't rely on the client to close a session. A timeout is probably your best option.

How to terminate session when the browser is closed in rails 3

Use Devise.

or if you don't want to, then expire the session as describe in Rails Security Guides.

Can't delete session properly in rails

The proper way to log a user out in Rails is by invalidating the session.

def log_out
reset_session
@current_user = nil
end

The sessions work in Rails is that the visitor is issued a cookie with a session id (a hash) when they first visit the site. This is linked to a stored session (also a cookie) and rails keeps track of which session ids are valid.

reset_session invalidates the session id on the server which is very important if you want to avoid things like session fixation and replay attacks. It also issues a new session id.

Doing session.delete(:user_id) only manipulates the session storage cookie held by the client. So if the client for example sends an older cookie they would still be logged in!

Then why is it not in the tutorial?

M. Hartl's Rails Tutorial book is not officially sanctioned and while its pretty good at explaining the key concepts it contains quite a lot which is very questionable.



Related Topics



Leave a reply



Submit