Ever wondered who is currently logged in to your app or how to kick them out? . You can do it using SessionRegistry.
(Disclaimer: UI is self-coded, not provided by Spring)
First, setup spring security configuration
Java config:
.and() .sessionManagement() .maximumSessions(1) // How many session the same user can have? This can be any number you pick .expiredUrl("/login?expired") .sessionRegistry(sessionRegistry)
And register the sessionRegistry bean:
(name = "sessionRegistry") public SessionRegistry sessionRegistry() { return new SessionRegistryImpl(); }
Or XML config, place this below
Now you can list currently active sessions
Inject a SessionRegistry and let’s see who’s currently logged in:
private SessionRegistry sessionRegistry; public ListgetActiveSessions() { List activeSessions = new ArrayList<>(); for(Object principal : sessionRegistry.getAllPrincipals()) { activeSessions.addAll(sessionRegistry.getAllSessions(principal, false)); } return activeSessions; }
SessionInformation object contains a lot of useful methods such as getPrincipal, getSessionId and getLastRequest. Have a look at the javadoc for more info.
What principal? I’m not in school anymore
Principal is just a fancy word for user in security speak. Note how SessionInformation returns a principal of type Object. If you use Spring Security your principal will most likely be the type of org.springframework.security.core.userdetails.User
Here’s how you can get the username from a User object:
SessionInformation session = ... // get the session info somehow Object principalObj = session.getPrincipal(); if (principalObj instanceof User) { User user = (User) principalObj; return user.getUsername(); }
If you need to kick someone out
The use case of this is not just for when you hated a particular user so much, but if user permission is updated, then you have to invalidate all active sessions for it to take effect.
public void logoutSession(String sessionId) { SessionInformation session = sessionRegistry.getSessionInformation(sessionId); if (session != null) { session.expireNow(); } }
Enjoy
And thanks to SO user dimas for posting an answer that inspires this post.