如何通过特定主体名称删除现有会话

How to remove existing sessions by specific principal name

我在我的项目中使用 Spring Session 1.3.0 和 Redis 后端。

我有一个用例,超级管理员可能会更新可能已经登录的现有用户的角色。我想在更改角色后删除这些用户的现有会话记录。

是否有 API 个 Spring 会话要存档?

    @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();
                    }
                }
            }
        }
    }

另想办法清除特定用户的会话,

@Autowired
FindByIndexNameSessionRepository sessionRepository;

sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
                username).keySet().forEach(session -> sessionRepository.delete((String) session));