Search code examples
jsfsessionjsf-2ejbinvalidation

JSF logout other users while maintaining my active session.


I am trying to logout a user in a jsf application as an admin while I maintain my session but the efforts are not yielding anything. A user can invalidate their own session easily in my application but what I want to achieve is a situation where another user say an admin can log out other users.

So my main question is how can I access the sessions of other users and is it possible to store the jsf sessions in the database?

Thanks for any assistance.


Solution

  • This code creates a Sessionlistener that manages the open sessions in a list that can be injected. Then you can inject the list of sessions via @SessionList

    SessionListener.java

    public class SessionListener implements HttpSessionListener {
    
      @Inject
      @SessionList
      private List<HttpSession> sessions;
    
      @Override
      public void sessionCreated(HttpSessionEvent event) {
        session.add(event.getSession());
      }
    
      @Override
      public void sessionDestroyed(HttpSessionEvent event) {
            session.remove(event.getSession());
      } 
    
    }
    

    SessionList.java

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Qualifier
    public @interface SessionList {
    }
    

    SessionProducer.Java

    @ApplicationScoped
    public class SessionProducer {
       private List<HttpSession> session;
    
       @Produces
       @SessionList
       public void List<Session> getSessions() {
          if(sessions == null) sessions = new LinkedList<HttpSession>();
          return sessions;
       }
    }