Created
August 14, 2015 15:19
-
-
Save xak2000/142c8f2e103020a5c897 to your computer and use it in GitHub Desktop.
Expire or remove spring session
This file contains hidden or 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
package test; | |
import java.security.Principal; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.security.access.prepost.PreAuthorize; | |
import org.springframework.security.core.session.SessionInformation; | |
import org.springframework.security.core.session.SessionRegistry; | |
import org.springframework.security.core.userdetails.UserDetails; | |
import org.springframework.web.bind.annotation.PathVariable; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RequestMethod; | |
import org.springframework.web.bind.annotation.RestController; | |
@RestController | |
@RequestMapping("/sessions") | |
public class SessionRegistryController { | |
@Autowired | |
SessionRegistry sessionRegistry; | |
/** | |
* Example of expiring specified user sessions | |
* @param user to expire sessions of | |
* @return current logged in users and sessions | |
*/ | |
@PreAuthorize("hasRole('ADMIN')") | |
@RequestMapping(value = "/{user}", method = RequestMethod.GET) | |
public List<Map<String, Object>> expireUserSessions(@PathVariable("user") String user) { | |
List<Object> allPrincipals = sessionRegistry.getAllPrincipals(); | |
List<Map<String, Object>> ret = new ArrayList<>(); | |
for (Object principal : allPrincipals) { | |
Map<String, Object> map = new HashMap<>(); | |
map.put("PRINCIPAL", principal); | |
ret.add(map); | |
List<SessionInformation> allSessions = sessionRegistry.getAllSessions(principal, true); | |
for (SessionInformation sessionInformation : allSessions) { | |
map = new HashMap<>(); | |
map.put("SESSION", sessionInformation); | |
ret.add(map); | |
if (principal instanceof UserDetails) { | |
UserDetails userDetails = (UserDetails) principal; | |
if (user.equals(userDetails.getUsername())) { | |
System.out.println("Expire session of user `" + user + "`. Session: " + sessionInformation); | |
sessionInformation.expireNow(); | |
sessionRegistry.removeSessionInformation(sessionInformation.getSessionId()); | |
} | |
} | |
} | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment