In this tutorial we assume that we already have grails application with Spring Security core plugin installed. We will explore how to retrieve currently logged-in users using the SessionRegistry.
What is SessionRegistry?
Maintains a registry of SessionInformation instances.
Inject sessionRegistry as a bean in resources.groovy as follows
import org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy
import org.springframework.security.web.session.ConcurrentSessionFilter
import org.springframework.security.core.session.SessionRegistryImpl
beans = {
sessionRegistry(SessionRegistryImpl)
sessionAuthenticationStrategy(ConcurrentSessionControlStrategy, sessionRegistry) {
maximumSessions = -1
}
concurrentSessionFilter(ConcurrentSessionFilter){
sessionRegistry = sessionRegistry
expiredUrl = ‘/login/concurrentSession’
}
}
import org.springframework.security.web.session.ConcurrentSessionFilter
import org.springframework.security.core.session.SessionRegistryImpl
beans = {
sessionRegistry(SessionRegistryImpl)
sessionAuthenticationStrategy(ConcurrentSessionControlStrategy, sessionRegistry) {
maximumSessions = -1
}
concurrentSessionFilter(ConcurrentSessionFilter){
sessionRegistry = sessionRegistry
expiredUrl = ‘/login/concurrentSession’
}
}
maximumSessions = -1 means application can create unlimited session
Using session factory we can easily get how many users are currently logged in as follows
def users = sessionRegistry.allPrincipals
GrailsUser loggedInUserInAnotherContext
println ‘All logged in users information’
users.each { user ->
println ‘username : ’ + user.username
}
GrailsUser loggedInUserInAnotherContext
println ‘All logged in users information’
users.each { user ->
println ‘username : ’ + user.username
}
this gives all users information.
Categories: Grails