sring Security3邊學邊寫(N)會話管理和並行控制

原文連接:http://sb33060418.iteye.com/blog/1953515javascript

在開發系統認證受權時,常常會碰到須要控制單個用戶重複登陸次數或者手動踢掉登陸用戶的需求。若是使用Spring Security 3.1.x該如何實現呢? 

Spring Security中可使用session management進行會話管理,設置concurrency control控制單個用戶並行會話數量,而且能夠經過代碼將用戶的某個會話置爲失效狀態以達到踢用戶下線的效果。 

本次實踐的前提是已使用spring3+Spring Security 3.1.x實現基礎認證受權。 

1.簡單實現 

要實現會話管理,必須先啓用HttpSessionEventPublisher監聽器。 
修改web.xml加入如下配置 
Java代碼 html

 收藏代碼

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


若是spring security是簡單的配置,如 
Java代碼 java

 收藏代碼

  1. <http use-expressions="true" access-denied-page="/login/noRight.jsp"   
  2.         auto-config="true">  
  3.     <form-login login-page="/login/login.jsp" default-target-url="/inde.jsp"   
  4.         authentication-failure-url="/login/login.jsp" always-use-default-target="true"/>  
  5. ...  
  6. </http>  


且沒有使用自定義的entry-point和custom-filter,只要在<http></http>標籤中添加<session-management>就能夠是實現會話管理和並行控制功能,配置以下 
Java代碼 web

 收藏代碼

  1. <!-- 會話管理 -->  
  2. <session-management invalid-session-url="/login/logoff.jsp">  
  3.     <!-- 並行控制 -->  
  4.     <concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/>  
  5. </session-management>  


其中invalid-session-url是配置會話失效轉向地址;max-sessions是設置單個用戶最大並行會話數;error-if-maximum-exceeded是配置當用戶登陸數達到最大時是否報錯,設置爲true時會報錯且後登陸的會話不能登陸,默認爲false不報錯且將前一會話置爲失效。 
配置完後使用不一樣瀏覽器登陸系統,就能夠看到同一用戶後來的會話不能登陸或將已登陸會話踢掉。 

2.自定義配置 

若是spring security的一段<http/>中使用了自定義過濾器<custom-filter/>(特別是FORM_LOGIN_FILTER),或者配置了AuthenticationEntryPoint,或者使用了自定義的UserDetails、AccessDecisionManager、AbstractSecurityInterceptor、FilterInvocationSecurityMetadataSource、UsernamePasswordAuthenticationFilter等,上面的簡單配置可能就不會生效了,Spring Security Reference Documentation裏面3.3.3 Session Management是這樣說的: 
Java代碼 spring

 收藏代碼

  1. If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly. More details can be found in the Session Management chapter.  


按照文章第12.3章中說明,auto-config已經失效,就須要自行配置ConcurrentSessionFilter、ConcurrentSessionControlStrategy和SessionRegistry,雖然配置內容和缺省一致。配置以下: 
Java代碼 express

 收藏代碼

  1. <http use-expressions="true" access-denied-page="/login/noRight.jsp" ...   
  2.     auto-config="false">  
  3.     <!-- 登陸fliter配置 -->  
  4.     <custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />  
  5.     <custom-filter position="FORM_LOGIN_FILTER"   
  6.         ref="myUsernamePasswordAuthenticationFilter" />  
  7.     <session-management   
  8.         session-authentication-strategy-ref="sessionAuthenticationStrategy"   
  9.         invalid-session-url="/login/logoff.jsp"/>  
  10. ...  
  11. </http>  
  12. ...  
  13. <beans:bean id="myUsernamePasswordAuthenticationFilter"   
  14.     class="com.sunbin.login.security.MyUsernamePasswordAuthenticationFilter">  
  15.     <beans:property name="sessionAuthenticationStrategy"   
  16.     ref="sessionAuthenticationStrategy" />  
  17.     <beans:property name="authenticationManager" ref="authenticationManager" />  
  18. </beans:bean>  
  19. <!-- sessionManagementFilter -->  
  20. <beans:bean id="concurrencyFilter"  
  21.     class="org.springframework.security.web.session.ConcurrentSessionFilter">  
  22.     <beans:property name="sessionRegistry" ref="sessionRegistry" />  
  23.     <beans:property name="expiredUrl" value="/login/logoff.jsp" />  
  24. </beans:bean>  
  25. <beans:bean id="sessionAuthenticationStrategy"  
  26.     class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">  
  27.     <beans:constructor-arg name="sessionRegistry"  
  28.         ref="sessionRegistry" />  
  29.     <beans:property name="maximumSessions" value="1" />  
  30. </beans:bean>  
  31. <beans:bean id="sessionRegistry"  
  32.     class="org.springframework.security.core.session.SessionRegistryImpl" />  


若是沒有什麼問題,配置完成後就能夠看到會話管理的效果了。 
須要和簡單配置同樣啓用HttpSessionEventPublisher監聽器。 

3.會話管理 

不少人作完第二步之後可能會發現,使用不一樣瀏覽器前後登陸會話仍是不受影響,這是怎麼回事呢?是配置的問題仍是被我忽悠了?我配置的時候也出現過這個問題,調試時看到確實走到了配置的sessionRegistry裏卻沒有效果,在網上找了好久也沒有找到答案,最後仍是隻能出動老辦法:查看源碼。 

ConcurrentSessionControlStrategy源碼部分以下: 
Java代碼 瀏覽器

 收藏代碼

  1. public void onAuthentication(Authentication authentication, HttpServletRequest request,  
  2.         HttpServletResponse response) {  
  3.     checkAuthenticationAllowed(authentication, request);  
  4.   
  5.     // Allow the parent to create a new session if necessary  
  6.     super.onAuthentication(authentication, request, response);  
  7.     sessionRegistry.registerNewSession(request.getSession().getId(), authentication.getPrincipal());  
  8. }  
  9.   
  10. private void checkAuthenticationAllowed(Authentication authentication, HttpServletRequest request)  
  11.         throws AuthenticationException {  
  12.   
  13.     final List<SessionInformation> sessions = sessionRegistry.getAllSessions(authentication.getPrincipal(), false);  
  14.   
  15.     int sessionCount = sessions.size();  
  16.     int allowedSessions = getMaximumSessionsForThisUser(authentication);  
  17.   
  18.     if (sessionCount < allowedSessions) {  
  19.         // They haven't got too many login sessions running at present  
  20.         return;  
  21.     }  
  22.   
  23.     if (allowedSessions == -1) {  
  24.         // We permit unlimited logins  
  25.         return;  
  26.     }  
  27.   
  28.     if (sessionCount == allowedSessions) {  
  29.         HttpSession session = request.getSession(false);  
  30.   
  31.         if (session != null) {  
  32.             // Only permit it though if this request is associated with one of the already registered sessions  
  33.             for (SessionInformation si : sessions) {  
  34.                 if (si.getSessionId().equals(session.getId())) {  
  35.                     return;  
  36.                 }  
  37.             }  
  38.         }  
  39.         // If the session is null, a new one will be created by the parent class, exceeding the allowed number  
  40.     }  
  41.   
  42.     allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);  
  43. }  
  44.   
  45. ...  
  46.   
  47. protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions,  
  48.         SessionRegistry registry) throws SessionAuthenticationException {  
  49.     if (exceptionIfMaximumExceeded || (sessions == null)) {  
  50.         throw new SessionAuthenticationException(messages.getMessage("ConcurrentSessionControlStrategy.exceededAllowed",  
  51.                 new Object[] {Integer.valueOf(allowableSessions)},  
  52.                 "Maximum sessions of {0} for this principal exceeded"));  
  53.     }  
  54.   
  55.     // Determine least recently used session, and mark it for invalidation  
  56.     SessionInformation leastRecentlyUsed = null;  
  57.   
  58.     for (SessionInformation session : sessions) {  
  59.         if ((leastRecentlyUsed == null)  
  60.                 || session.getLastRequest().before(leastRecentlyUsed.getLastRequest())) {  
  61.             leastRecentlyUsed = session;  
  62.         }  
  63.     }  
  64.   
  65.     leastRecentlyUsed.expireNow();  
  66. }  


checkAuthenticationAllowed是在用戶認證的時候被onAuthentication調用,該方法首先調用SessionRegistryImpl.getAllSessions(authentication.getPrincipal(), false)得到用戶已登陸會話。若是已登陸會話數小於最大容許會話數,或最大容許會話數爲-1(不限制),或相同用戶在已登陸會話中從新登陸(有點繞口,但有時候會有這種用戶本身在同一會話中重複登陸的狀況,不注意就會重複計數),就調用SessionRegistry.registerNewSession註冊新會話信息,容許本次會話登陸;不然調用 
allowableSessionsExceeded方法拋出異常或最老的會話置爲失效。 

接下來看SessionRegistryImpl類的源碼,關鍵就是getAllSessions方法: 
Java代碼 session

 收藏代碼

  1. public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {  
  2.     final Set<String> sessionsUsedByPrincipal = principals.get(principal);  
  3.   
  4.     if (sessionsUsedByPrincipal == null) {  
  5.         return Collections.emptyList();  
  6.     }  
  7.   
  8.     List<SessionInformation> list = new ArrayList<SessionInformation>(sessionsUsedByPrincipal.size());  
  9.   
  10.     for (String sessionId : sessionsUsedByPrincipal) {  
  11.         SessionInformation sessionInformation = getSessionInformation(sessionId);  
  12.   
  13.         if (sessionInformation == null) {  
  14.             continue;  
  15.         }  
  16.   
  17.         if (includeExpiredSessions || !sessionInformation.isExpired()) {  
  18.             list.add(sessionInformation);  
  19.         }  
  20.     }  
  21.   
  22.     return list;  
  23. }  


SessionRegistryImpl本身維護一個private final ConcurrentMap<Object,Set<String>> principals,並以用戶信息principal做爲key來保存某一用戶全部已登陸會話編號。 

再次調試代碼時發現,principals中明明有該用戶principal但principals.get(principal)取到的是null,而後認證成功,又往principals裏面put了一個新的principal對象爲key。查看debug控制檯發現principals中兩次登陸的principal內容一致,但卻沒法從map中取得,這說明新登陸的principal和舊的不相等。 

再查看ConcurrentHashMap.get(Object key)方法源碼就能找到問題了。咱們知道Map中取值的時候都是要邏輯上相等的,即hash值相等且equals。若是兩次登陸的principal邏輯上不相等,天然被認爲是兩個用戶,不會受最大會話數限制了。 

這裏會話管理不生效的緣由是在自定義的UserDetails。通常配置Spring Security都會本身實現用戶信息接口 
Java代碼 app

 收藏代碼

  1. public class User implements UserDetails, Serializable  


並實現幾個主要方法isAccountNonExpired()、getAuthorities()等,但卻忘記重寫繼承自Object類的equals()和hashCode()方法,致使用戶兩次登陸的信息沒法被認爲是同一個用戶。 

查看Spring Security的用戶類org.springframework.security.core.userdetails.User源碼 
Java代碼 jsp

 收藏代碼

  1. /** 
  2.  * Returns {@code true} if the supplied object is a {@code User} instance with the 
  3.  * same {@code username} value. 
  4.  * <p> 
  5.  * In other words, the objects are equal if they have the same username, representing the 
  6.  * same principal. 
  7.  */  
  8. @Override  
  9. public boolean equals(Object rhs) {  
  10.     if (rhs instanceof User) {  
  11.         return username.equals(((User) rhs).username);  
  12.     }  
  13.     return false;  
  14. }  
  15.   
  16. /** 
  17.  * Returns the hashcode of the {@code username}. 
  18.  */  
  19. @Override  
  20. public int hashCode() {  
  21.     return username.hashCode();  
  22. }  


只要把這兩個方法加到本身實現的UserDetails類裏面去就能夠解決問題了。 

4.本身管理會話 

如下部份內容參考wei_ya_wen的http://blog.csdn.net/wei_ya_wen/article/details/8455415這篇文章。 

管理員踢出一個帳號的實現參考以下: 
Java代碼 

 收藏代碼

  1. @RequestMapping(value = "logout.html")   
  2. public String logout(String sessionId, String sessionRegistryId, String name, HttpServletRequest request, ModelMap model){      
  3.     List<Object> userList=sessionRegistry.getAllPrincipals();    
  4.     for(int i=0; i<userList.size(); i++){    
  5.         User userTemp=(User) userList.get(i);        
  6.         if(userTemp.getName().equals(name)){            
  7.             List<SessionInformation> sessionInformationList = sessionRegistry.getAllSessions(userTemp, false);    
  8.             if (sessionInformationList!=null) {     
  9.                 for (int j=0; j<sessionInformationList.size(); j++) {    
  10.                     sessionInformationList.get(j).expireNow();    
  11.                     sessionRegistry.removeSessionInformation(sessionInformationList.get(j).getSessionId());    
  12.                     String remark=userTemp.getName()+"被管理員"+SecurityHolder.getUsername()+"踢出";    
  13.                     loginLogService.logoutLog(userTemp, sessionId, remark);     //記錄註銷日誌和減小在線用戶1個    
  14.                     logger.info(userTemp.getId()+"  "+userTemp.getName()+"用戶會話銷燬," + remark);    
  15.                 }    
  16.             }    
  17.         }    
  18.     }    
  19.     return "auth/onlineUser/onlineUserList.html";    
  20. }    


若是想完全刪除, 須要加上 
Java代碼 

 收藏代碼

  1. sessionRegistry.removeSessionInformation(sessionInformationList.get(j).getSessionId());  


不須要刪除用戶,由於SessionRegistryImpl在removeSessionInformation時會自動判斷用戶是否無會話並刪除用戶,源碼以下 
Java代碼 

 收藏代碼

  1. if (sessionsUsedByPrincipal.isEmpty()) {  
  2.             // No need to keep object in principals Map anymore  
  3.             if (logger.isDebugEnabled()) {  
  4.                 logger.debug("Removing principal " + info.getPrincipal() + " from registry");  
  5.             }  
  6.             principals.remove(info.getPrincipal());  
  7.         }  
相關文章
相關標籤/搜索