Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove existing sessions by specific principal name

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?

like image 705
Kane Avatar asked Dec 23 '22 20:12

Kane


2 Answers

    @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();
                    }
                }
            }
        }
    }
like image 62
mirmdasif Avatar answered Dec 28 '22 06:12

mirmdasif


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));
like image 29
Kane Avatar answered Dec 28 '22 05:12

Kane