GRAILS: how to get the number of currently signed in users via spring security core plugin?

后端 未结 2 1936
误落风尘
误落风尘 2020-12-09 13:52

my problem is, that i want to limit the number of users that can simultaneously be logged in my application (this value is stored in the database). first i tried to do that

相关标签:
2条回答
  • 2020-12-09 14:39

    First I was thinking of counting users which logged in given period, but this can be inaccurate.

    I think you could cache user id and time of his last action. Then you could write filter, that on every action updates this cache if user is logged in. Then you could just count items that are in the cache. If your cache would be small, you could also iterate over it and remove users that are inactive for eg. five minutes (or any other, like session expiration - btw: sessionId could also be stored there, so you could check if that session is still valid). If cache big, scheduled job could take care of it.

    0 讨论(0)
  • 2020-12-09 14:45

    Thanks for your answer! Now i got it...

    The steps i took are:

    Defining the beans:

    import org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy 
    import org.springframework.security.web.session.ConcurrentSessionFilter 
    import org.springframework.security.core.session.SessionRegistryImpl 
    import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
    
    beans = { 
    
            sessionRegistry(SessionRegistryImpl) 
    
            sessionAuthenticationStrategy(ConcurrentSessionControlStrategy, sessionRegistry) { 
                    maximumSessions = -1 
            } 
    
            concurrentSessionFilter(ConcurrentSessionFilter){ 
                    sessionRegistry = sessionRegistry 
                    expiredUrl = '/login/concurrentSession' 
            } 
    } 
    

    then in my controller i injected:

    class SystemController {    
    
        def sessionRegistry
    

    and the check, how many sessions are currently in use:

        def sessioncount = {
            def cnt = 0
    
            sessionRegistry.getAllPrincipals().each{
                cnt += sessionRegistry.getAllSessions(it, false).size()
            }    
    
            render cnt
        }
    

    additional steps that must be made:

    1. install templates from grails (grails install-templates)
    2. add listener to web.xml:

      <listener>
          <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
      </listener>
      

    and now it works!

    great! :)

    (now the next steps are - defining an eventlistener (when the user logs in) check the number of licenses(sessions) and permit or deny access to him. but i think that´s not that tricky... we´ll see...)

    0 讨论(0)
提交回复
热议问题