2016-07-05 106 views
0

春季安全:
我想用所謂的牽引方式註銷:發生了會話超時或註銷自身用戶...
反正在這些方面,在HttpSessionEventPublisherSessionRegistry稱爲destroyedSession時從sessionIds列表中刪除SessionInformation ...


當我使用下面的方法強制註銷特定用戶時,此方法僅在「過期」SessionInformationSessionRegistry。現在,當我從SessionRegistry獲得所有在線用戶「getAllPrincipals()」時,會話過期的用戶就在列表中!註銷特定會話ID

@Override 
public boolean forceLogOut(int userId){ 
    for (Object username: sessionRegistry.getAllPrincipals()) { 
     User temp = (User) username; 
     if(temp.getId().equals(userId)){ 
      for (SessionInformation session : sessionRegistry.getAllSessions(username, false)) { 
       session.expireNow(); 
      } 
     } 
    } 
    return true; 
} 

我怎麼能註銷「特定用戶」或「的sessionId」該會話對象從「Web服務器」和「會議註冊表」中刪除?
我在網上搜索,發現HttpSessionContext在Servlet API中可以從特定sessionId獲取HttpSession。然後使會話無效。但我認爲這種方法並不完全有用!
(注意,這個類已棄用!)

什麼是最好的方法?我是否錯了?

+0

sessionRegistry.getSessionInformation(的sessionId).expireNow(); Spring將標記此會話過期。來自此會話的任何進一步請求都會調用註銷。 –

+0

這是真的,但是如果用戶不發送任何請求,並且會話超時最大不超過1小時(超時不是超時),那麼當使用'getAllPrincipals()'時,此方法返回所有原則,包括在線會話和到期會話...這是我的問題...! –

回答

0

嘗試這樣的:

@RequestMapping(value="/logout", method = RequestMethod.GET) 
    public String logoutPage (HttpServletRequest request, HttpServletResponse response){ 
     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     if (auth != null){  
      //new SecurityContextLogoutHandler().logout(request, response, auth); 
      persistentTokenBasedRememberMeServices.logout(request, response, auth); 
      SecurityContextHolder.getContext().setAuthentication(null); 
     } 
     return "redirect:/login?logout"; 
    } 

要註銷特定的會話ID檢查鏈接: how to log a user out programmatically using spring security

+0

感謝您的回覆...我想強制註銷一個用戶與另一個用戶,然後立即從'SessionRegistry'和我的Web服務器中刪除用戶的會話對象..我認爲這種方法註銷用戶與自己。 –

+0

是的,你是對的,它自己註銷用戶.. – FuSsA

+0

你有一個想法,我該怎麼辦?我想管理在線用戶和強制註銷後一個用戶看到在線用戶。當我使用'getAllPrincipals()',過期的會話在列表中...! –