spring security core plugin - invalidate a user session

456 Views Asked by At

I am using grails 4.0.3 and I am trying to logout a user programmatically. I search for this but all the solutions that I found are for grails 2 and are not working for grails 4.

Like - force logout for authenticated user using spring security plugin

Does anyone have any idea how to invalidate a user session?

2

There are 2 best solutions below

0
On BEST ANSWER

Does anyone have any idea how to invalidate a user session?

In a controller you can invoke session.invalidate().

If you want to access the session from some other context, you could have that class implement the grails.web.api.ServletAttributes trait, which will provide the session property to that class and then session.invalidate() may be called from there.

0
On

Jeff's solution works for the current user's session only. If you want to logout/invalidate all the sessions (or all the sessions of a particular user) then you can use this solution.

Make a custom session listener class-

class MyCustomSessionListener implements HttpSessionListener {
  Map<String, HttpSession> sessions = [:].asSynchronized()

  void sessionCreated(HttpSessionEvent se) {
    sessions.put(se.session.id, se.session)
  }

  void sessionDestroyed(HttpSessionEvent se) {
    sessions.remove(se.session.id)
  }

  void invalidateAllSessionsOfUser(String username) {
    List<HttpSession> sessionsList = []
    sessions.each { sessionId, sess ->
      SecurityContext sc = sess[SPRING_SECURITY_CONTEXT_KEY]
      if (sc.authentication.principal.username == username) {
        sessionsList.add(sess)
      }
    }
    sessionsList*.invalidate()
  }
  
  void invalidateAllSessions() {
    List<HttpSession> sessionsList = []
    sessions.each { sessionId, sess ->
      sessionsList.add(sess)
    }
    sessionsList*.invalidate()
  }
}

and make an entry in resources.groovy

beans = {
  myCustomSessionListener(MyCustomSessionListener)
}