Skip to content

Invalidate session programatically  #1044

@mrshawn191

Description

@mrshawn191

Hi in my project I have to support both redis and inmemory session repository.

The problem is whenever a user object is mutated in database, we invalidate session and replace with the new updated one, this logic seems to cause problem.

    @Transactional
    public void enableOrDisable(User user) {
        Assert.notNull(user, "Cannot enable or disable on a non existing user");
        userDao.enableOrDisable(user);
        invalidate(user.getUsername());
    }


    @SuppressWarnings("unchecked")
    private void invalidate(String username) {
        final ExpiringSession session = onUserRetrieval(username);
        User user = userDao.findByUsername(username);
        if (null != session && null != user) {
            user.eraseCredentials();
            log.info("<invalidate(): Found existing session trying invalidate {} with {}", toJson(session), toJson(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)));
            final SecurityContext context = SecurityContextHolder.createEmptyContext();
            context.setAuthentication(new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()));
            session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
            log.info("<invalidate(): Replaced old session with {} and {}", toJson(session), toJson(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)));
            sessionRepository.save(session);
            SecurityContextHolder.setContext(context);
        }
    }

    @SuppressWarnings("unchecked")
    private ExpiringSession onUserRetrieval(String username) {
        return (ExpiringSession) this.sessionRepository
                .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username)
                .values()
                .stream()
                .findFirst()
                .orElse(null);
    }

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions