Tigraine

Daniel Hoelbling-Inzko talks about programming

How to expire all active Sessions in Rails 3

Posted by Daniel Hölbling on August 3, 2012

I know this sounds like a very simple task to do, but since I just spent half an hour reading up on how Sessions in Rails work I decided it's time to put this up so I can Google it again next time :)

First off, you need to know how you are storing sessions in your application. Rails supports 3 types of session storage: Stored on Disk, in the Database or through Cookies in the client. You can check which one you are using in /config/initializers/session_store.rb.

Cookie based session storage

Rails 3 defaults to storing the session in the client using a session cookie. This means that the user_id along with all the data you put into the session hash is serialized into the cookie and sent to the client. It's also not encrypted, only BASE64 encoded so if you are storing anything sensitive in there you are doing it wrong.

But for simple things like the current user_id the cookie based session store is just fine and also a lot faster than the alternatives.

Expiring the cookie though is a bit more involved since you can't reach out to all clients and delete their cookies at once. But, and that's the important part for what I was doing: This cookie is signed with a SHA-512 digest using a secret key that is only present on the server. So the cookie cannot be tampered with on the client, and this is also your avenue of attack when trying to expire all cookies:

Simply change the secret that is used to sign the cookies. All previous cookies are invalidated as their digest is no longer valid.

Doing so is simple, first generate a new secret using rake:

$ rake secret 10dfec4781b682762a731a5e88af78521fc3e0f...

Then copy/paste that new secret into your config/initializers/secret_token.rb:

MyApp::Application.config.secret_token = '10dfec4781b682762a731a5e88...'

Once done deploy the application and all existing sessions are invalid at once.

Database backed session storage

If you are using the Database to store the session it's rather trivial to expire all existing sessions using rake:

rake db:sessions:clear

File based session storage

Like with the database simply run the following rake command:

rake tmp:sessions:clear

Hope this helps..

Filed under programmierung, rails, ruby
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more