简体   繁体   中英

Using the Play cache API for storing user session ids?

What I want to do is to implement a simple authentication mechanism in my Play application. Unlike it is done in Play's ZenTask Tutorial , I don't think it is a good idea to store the session id of an authenticated user solely in a session (which, in Play, is a signed cookie), because then the server does not have any control of the login state of users that are already logged in. Image a user account gets deleted or you want to enforce the logout of a specific user - in case this user has a valid cookie, he still will be authenticated successfully on the next request because the server will only check for the presence of a session id in the cookie.

So I'm wondering: what about using the Play cache API for storing session ids of users? On every page request, the session id included in the request could be looked up in the cache. If it is not there, then the user has to log in.

The benefits from my point of view:

  • the mentioned problem is gone. Deleted users or users for which a logout is enforced are no longer logged in because the cache contents can be changed on the server side
  • At the moment, I don't need more than one machine for the play application, so Play could internally use EHCache. In case I need to scale and have to deploy additional machines in the future, EHCache could be replaced by an external and distributed memached server without having to change the code.

What do you think?

I think it's a perfectly valid approach, and, to give an example, the play2-auth library provides a way to do this with its CacheIdContainer .

As the author there points out the main advantage of this stateful approach over one using session cookies is that it invalidates a user's prior sessions when they log in somewhere else.

The main disadvantage, at least if you're using Play's default EHCache , is that sessions will not persist across server restarts, but you could use something like memcache to get around that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM