Play framework how do sessions and cookies work?

authentication, cookies, java, playframework-2.0, scala

Solution

You didn't specify how do you authenticate users, so I just guess, that you;re using simple sample which is... simple.

It uses user's id to identify the user, and check if signed session cookie wasn't manipulated, therefore if you'll recreate the cookie with proper signature it will be valid still.

You should create some area for session's keys on the server side ie. in DB or in memory cache (Which will be faster than DB). Its key should be randomly generated (and preferebly quite long) for each successful login action, and should also contain data for identifying user, expiration date etc. Next you should put this random `sess_key` to the Play's session instead email address of logged user or id of his row in DB, and after logout and/or expiration date it should be removed. In such case even if you'll loose the cookie after logout it will be impossible to login properly with non-esixting `sess_key`.

AFAIR standard memory cache will be purged at every restart of the application, to make sure that all `sess_keys` from DB will be removed as well you can use Global object and truncate the table in `onStart(...)` method.

Problem

How does play validate a cookie? - I noticed that after I restarted the server I was still logged in even though I don't presist any session data in the database. - I also noticed that I could set the date on the server to be larger that the exipry date of the cookie and still I was logged in. - I logged out (saved the cookie to a text file) and the browser lost the cookie. Then I recreated the cookie from the text file and I was logged in again. The cookie looks like this: PLAY_SESSION=e6443c88da7xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-userid%3A1 ``` // My logout code def logout() = Action { Ok("").withNewSession } ``` From the documentation Discarding the whole session There is special operation that discards the whole session: ``` Ok("Bye").withNewSession ```

Original source