spring-boot redis : How to invalidate all sessions of a user?

I would like to know you that you are following the correct path for invalidating the user sessions

    usersSessions.forEach((session) -> {        
        sessionRegistry.getSessionInformation(session.getId()).expireNow();
    });

Somethings to note

SessionInformation.expireNow()

is not mean to remove entries from the redis database, it just appends the expired attribute to session as you rightly mentioned.

But how this invalidates the session of the user?

Here comes the ConcurrentSessionFilter into play where .doFilter() method does the trick of automatically logging out

Here is the snippet for ConcurrentSessionFilter

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    HttpSession session = request.getSession(false);

    if (session != null) {
        SessionInformation info = sessionRegistry.getSessionInformation(session
                .getId());

        if (info != null) {
            if (info.isExpired()) {
                // Expired - abort processing
                doLogout(request, response);

                String targetUrl = determineExpiredUrl(request, info);

                if (targetUrl != null) {
                    redirectStrategy.sendRedirect(request, response, targetUrl);

                    return;
                }
                else {
                    response.getWriter().print(
                            "This session has been expired (possibly due to multiple concurrent "
                                    + "logins being attempted as the same user).");
                    response.flushBuffer();
                }

                return;
            }
            else {
                // Non-expired - update last request date/time
                sessionRegistry.refreshLastRequest(info.getSessionId());
            }
        }
    }

    chain.doFilter(request, response);
}

Cheers to that!


@Autowired
private RedisIndexedSessionRepository redisIndexedSessionRepository;

redisIndexedSessionRepository.findByPrincipalName('your@login').keySet().forEach(redisIndexedSessionRepository::deleteById);

Try this

usersSessions.forEach((session) -> {        
        sessionRegistry.delete(session.getId());
  });