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

假装没事ソ 提交于 2019-11-28 08:50:26

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...)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!