Home Ask Login Register

Developers Planet

Your answer is one click away!

Ilan.K February 2016

spring security, how to expire all sessions of a user

I have to solve the following scenario, in a Spring Security 3.2.5-RELEASE with Spring Core 4.1.2-RELEASE application running Java 1.7 on wildfly 8.1.

  1. user 'bob' logs in
  2. and Admin deletes 'bob'
  3. if 'bob' logs out, he can't log in. again but he`s current session remains active.
  4. i want to kick 'bob' out

    //this doesn't work
    for (final SessionInformation session :    sessionRegistry.getAllSessions(user, true)) {


Ilan.K February 2016

  1. add application event listener to track HttpSessionCreatedEvent and HttpSessionDestroyedEvent and register it as an ApplicationListener and maintain a cache of SessionId to HttoSession.
  2. (optional) add your own ApplicationEvent class AskToExpireSessionEvent -
  3. in you user management service add dependencies to SessionRegistry and ApplicationEventPublisher so that you could list through the currently active user sessions and find the ones (cause there could be many) which are active for the user you are looking for i.e. 'bob'
  4. when deleting a user dispatch an AskToExpireSessionEvent for each of he's sessions.
  5. use a weak reference HashMap to track the sessions

user service:

     public class UserServiceImpl implements UserService {

      /** {@link SessionRegistry} does not exists in unit tests */
      @Autowired(required = false)
      private Set<SessionRegistry> sessionRegistries;

      private ApplicationEventPublisher publisher;

      * destroys all active sessions.
      * @return <code>true</code> if any session was invalidated^
      * @throws IllegalArgumentException
      public boolean invalidateUserByUserName(final String userName) {
              if(null == StringUtils.trimToNull(userName)) {
                      throw new IllegalArgumentException("userName must not be null or empty");
              boolean expieredAtLeastOneSession = false;
              for (final SessionRegistry sessionRegistry : safe(sessionRegistries)) {
                      findPrincipal: for (final Object principal : sessionRegistry.getAllPrincipals()) {
                              if(principal instanceof IAuthenticatedUser) {
                                      final IAuthenticatedUser user = 

Post Status

Asked in February 2016
Viewed 1,179 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life