4

I'm using Spring Session 1.3.0 with Redis backend in my project.

I have an use case that the super admin might update the roles of existing user who might already logged in. I want to delete the existing session records for those users after changing their roles.

Is there API of Spring Session to archive it?

dur
  • 15,689
  • 25
  • 79
  • 125
Kane
  • 8,035
  • 7
  • 46
  • 75

2 Answers2

7
    @Autowired
    private SessionRegistry sessionRegistry;

    public void expireUserSessions(String username) {
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            if (principal instanceof User) {
                UserDetails userDetails = (UserDetails) principal;
                if (userDetails.getUsername().equals(username)) {
                    for (SessionInformation information : sessionRegistry.getAllSessions(userDetails, true)) {
                        information.expireNow();
                    }
                }
            }
        }
    }
mirmdasif
  • 6,014
  • 2
  • 22
  • 28
6

Also work out another way to clean sessions of specific user,

@Autowired
FindByIndexNameSessionRepository sessionRepository;

sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
                username).keySet().forEach(session -> sessionRepository.delete((String) session));
Kane
  • 8,035
  • 7
  • 46
  • 75
  • Deleting sessions prematurely has some side effects if you allow multiple sessions of a single user. Have a look on this question. http://stackoverflow.com/questions/22370819/how-to-log-a-user-out-programmatically-using-spring-security – mirmdasif Feb 08 '17 at 07:01
  • @mirmdasif it's an interesting finding. I'm wondering why spring/spring security still gives the permission of request with invalid session id(expired or removed). – Kane Feb 08 '17 at 07:19