2013-04-23 89 views
0

我如何測試用戶是否登錄或不在Grails中使用spring security core插件?測試用戶是否登錄

我想知道我在我的數據庫中的每個用戶,如果用戶是在線還是沒有, 我無法弄清楚如何與彈簧安全插件做到這一點

+1

http://stackoverflow.com/questions/6648100/grails-how-to-get-the-number-of-currently-signed-in-users-via-spring-security-c – 2013-04-23 15:59:07

+0

感謝塞爾吉奧,我已經做了像那個鏈接,現在我有權訪問sessionRegistry,我需要我想我必須使用方法:getAllSessions(Object principal,boolean includeExpiredSessions),這讓我獲得所有已知的會話爲指定的主體,那麼我可以知道用戶是否有活動會話或不活動,但有一件事仍然不清楚,這種方法的主體對象的類型是什麼, 我嘗試從我的grails項目中的用戶實例,但它doesn 't work – 2013-04-24 10:11:24

+1

如果你打印instance.class,你可以看到他的類型。你也可以看到該方法返回的類型。 – 2013-04-24 12:08:27

回答

0

我採取的步驟是:

定義豆類:

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' 
     } 
} 

從Grails的安裝模板(Grails的安裝模板)

添加監聽器web.x毫升:

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

在我的服務注入的SessionRegistry:

def sessionRegistry 

...

def getSessionInformations(User user){ 
     def userDetails = userDetailsService.loadUserByUsername(user.username) 
     def sessionInfo = sessionRegistry.getAllSessions(userDetails, true) 
     return sessionInfo 
    } 

def isOnline(User user) { 
if (getSessionInformations(user)){return true } else { return false } 
} 
+0

這是不正確的。如果用戶登錄並關閉瀏覽器,會話保持打開狀態,並且您的代碼將返回,他仍然登錄。我不知道一段時間之後未使用的會話是否會關閉。你如何解決這個問題? – confile 2013-05-19 20:05:31

+0

哈米拉你有這個工作嗎?如果是,你可以發佈你的工作代碼嗎?謝謝 !洛倫佐 – Merlin 2014-05-03 16:16:22