Skip to content

Instantly share code, notes, and snippets.

@thinkbigthings
Last active July 28, 2020 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkbigthings/b7c9785ea5df46d9b67558cd4dc4918c to your computer and use it in GitHub Desktop.
Save thinkbigthings/b7c9785ea5df46d9b67558cd4dc4918c to your computer and use it in GitHub Desktop.
Get other users' sessions (as admin) to log them out in Spring Security
With sessions it might be necessary to logout on password change. Also the Logout button from UI should additionally logout on the server.
https://stackoverflow.com/questions/44359792/log-out-user-by-admin-spring-security
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#jc-logout
// in WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http
...
.sessionManagement()
.maximumSessions(-1)
.sessionRegistry(sessionRegistry());
}
@Bean
SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
// in a Service, inject the same SessionRegistry and call it like so
public void logoutUser(String username) {
final boolean includeExpiredSessions = false;
List<SessionInformation> userSessions = sessionRegistry.getAllPrincipals().stream()
.filter(org.springframework.security.core.userdetails.User.class::isInstance)
.map(org.springframework.security.core.userdetails.User.class::cast)
.filter(user -> user.getUsername().equals(username))
.peek(user -> System.out.println("Finding sessions for " + user.getUsername()))
.flatMap(user -> sessionRegistry.getAllSessions(user, includeExpiredSessions).stream())
.collect(toList());
System.out.println("Expiring sessions: " + userSessions.size());
userSessions.forEach(s -> s.expireNow());
userSessions.forEach(s -> sessionRegistry.removeSessionInformation(s.getSessionId()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment