Is it possible to invalidate a spring security session?

You can’t usually invalidate a user session(s) immediately you change their account information without resorting to a container specific API, since the only way to access the HttpSession is through the HttpServletRequest object.

Instead you can cache the username in an in-memory store and consult it either in a filter or a custom AccessDecisionVoter. Using a flag in the user table isn’t really a great idea, since the flag is transient in nature (it is irrelevant after a server restart) and it’s better to avoid the performance hit of a database query on every request.

There’s a blog article on using custom voters for this kind of thing. It’s out of date but the general approach is sound.

Another approach is to use Spring Security’s SessionRegistry which is part of the session-management functionality. Normally this is used to limit the number of sessions a user can have but can also be used to list currently authenticated users or mark their session for expiry.

It might also be an idea to just reload the user’s privileges, rather than logging them out completely.

Leave a Comment