-->

Store and invalidate Java HttpSession from differe

2019-03-03 06:06发布

问题:

Okay. What I want to do is be able to, when I update a user, invalidate any session that they currently have in order to force a refresh of credentials. I don't care about being able to directly access the session-specific user data. Ideally, I would also be able to restrict users to one session by a similar manner.

What I tried doing is creating a HashMap using the username as key and HttpSession as the value (my actual setup is a little more involved, but after repeated seemingly inexplicable failures, I boiled it down to this simple test). However, whenever I attempt to tell the retrieved HttpSession to invalidate, it seems to be invalidating the current [admin] session. Is HttpSession inextricably bound to the current request?

Or is there an entirely different way to deal with this?

If it happens to matter, I'm using Jetty 6.1.26.

回答1:

There's no straight forward way. The easiest way I can think of is to keep a flag on the database (or a cahche) and check it's validity on each request.

Or you can implement a HTTP Session listener and keep a HashMap of user sessions that can be accessed and invalidated.

I haven't tried any of these out so I don't know of any performance issues. But it should be acceptable for most applications.



回答2:

Well, as far as I can tell, there's no way around it. Using a request-scoped bean didn't work as I expected (although it did give me good insights into how Spring operates, intercepting field accesses). I ended up using a dirty flag on my SessionHandler (a session-scoped bean) with a very high-priority aspect checking and, if necessary, calling invalidate() on the session in the user's next request. I still ended up having all my SessionHandlers register with a SessionManager, and a @PreDestroy method to unregister them in order to avoid a bunch of null entries in the map.