Last active
July 28, 2020 09:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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