spring security 自定义filter 会话失效问题

来源:互联网 发布:简单php文章管理系统 编辑:程序博客网 时间:2024/05/16 10:34
在开发系统认证授权时,经常会碰到需要控制单个用户重复登录次数或者手动踢掉登录用户的需求。如果使用Spring Security 3.1.x该如何实现呢? 

Spring Security中可以使用session management进行会话管理,设置concurrency control控制单个用户并行会话数量,并且可以通过代码将用户的某个会话置为失效状态以达到踢用户下线的效果。 

本次实践的前提是已使用spring3+Spring Security 3.1.x实现基础认证授权。 

1.简单实现 

要实现会话管理,必须先启用HttpSessionEventPublisher监听器。 
修改web.xml加入以下配置 
Java代码  收藏代码
  1. <listener>  
  2.     <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>  
  3. </listener>  

如果spring security是简单的配置,如 
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代码  收藏代码
  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代码  收藏代码
  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代码  收藏代码
  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代码  收藏代码
  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代码  收藏代码
  1. public class User implements UserDetails, Serializable  

并实现几个主要方法isAccountNonExpired()、getAuthorities()等,但却忘记重写继承自Object类的equals()和hashCode()方法,导致用户两次登录的信息无法被认为是同一个用户。 

查看Spring Security的用户类org.springframework.security.core.userdetails.User源码 
Java代码  收藏代码
  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.         }  
0 0
原创粉丝点击