日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
SpringSecurity系列之只允許一臺(tái)設(shè)備在線

[[399043]]

創(chuàng)新互聯(lián)建站堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、成都外貿(mào)網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的比如網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

 登錄成功后,自動(dòng)踢掉前一個(gè)登錄用戶,松哥第一次見(jiàn)到這個(gè)功能,就是在扣扣里邊見(jiàn)到的,當(dāng)時(shí)覺(jué)得挺好玩的。

自己做開(kāi)發(fā)后,也遇到過(guò)一模一樣的需求,正好最近的 Spring Security 系列正在連載,就結(jié)合 Spring Security 來(lái)和大家聊一聊這個(gè)功能如何實(shí)現(xiàn)。

1.需求分析

在同一個(gè)系統(tǒng)中,我們可能只允許一個(gè)用戶在一個(gè)終端上登錄,一般來(lái)說(shuō)這可能是出于安全方面的考慮,但是也有一些情況是出于業(yè)務(wù)上的考慮,松哥之前遇到的需求就是業(yè)務(wù)原因要求一個(gè)用戶只能在一個(gè)設(shè)備上登錄。

要實(shí)現(xiàn)一個(gè)用戶不可以同時(shí)在兩臺(tái)設(shè)備上登錄,我們有兩種思路:

后來(lái)的登錄自動(dòng)踢掉前面的登錄,就像大家在扣扣中看到的效果。

如果用戶已經(jīng)登錄,則不允許后來(lái)者登錄。

這種思路都能實(shí)現(xiàn)這個(gè)功能,具體使用哪一個(gè),還要看我們具體的需求。

在 Spring Security 中,這兩種都很好實(shí)現(xiàn),一個(gè)配置就可以搞定。

2.具體實(shí)現(xiàn)

2.1 踢掉已經(jīng)登錄用戶

想要用新的登錄踢掉舊的登錄,我們只需要將最大會(huì)話數(shù)設(shè)置為 1 即可,配置如下:

 
 
 
 
  1. @Override 
  2. protected void configure(HttpSecurity http) throws Exception { 
  3.     http.authorizeRequests() 
  4.             .anyRequest().authenticated() 
  5.             .and() 
  6.             .formLogin() 
  7.             .loginPage("/login.html") 
  8.             .permitAll() 
  9.             .and() 
  10.             .csrf().disable() 
  11.             .sessionManagement() 
  12.             .maximumSessions(1); 

maximumSessions 表示配置最大會(huì)話數(shù)為 1,這樣后面的登錄就會(huì)自動(dòng)踢掉前面的登錄。這里其他的配置都是我們前面文章講過(guò)的,我就不再重復(fù)介紹,文末可以下載案例完整代碼。

配置完成后,分別用 Chrome 和 Firefox 兩個(gè)瀏覽器進(jìn)行測(cè)試(或者使用 Chrome 中的多用戶功能)。

  1. Chrome 上登錄成功后,訪問(wèn) /hello 接口。
  2. Firefox 上登錄成功后,訪問(wèn) /hello 接口。
  3. 在 Chrome 上再次訪問(wèn) /hello 接口,此時(shí)會(huì)看到如下提示:
 
 
 
 
  1. This session has been expired (possibly due to multiple concurrent logins being attempted as the same user). 

可以看到,這里說(shuō)這個(gè) session 已經(jīng)過(guò)期,原因則是由于使用同一個(gè)用戶進(jìn)行并發(fā)登錄。

2.2 禁止新的登錄

如果相同的用戶已經(jīng)登錄了,你不想踢掉他,而是想禁止新的登錄操作,那也好辦,配置方式如下:

 
 
 
 
  1. @Override 
  2. protected void configure(HttpSecurity http) throws Exception { 
  3.     http.authorizeRequests() 
  4.             .anyRequest().authenticated() 
  5.             .and() 
  6.             .formLogin() 
  7.             .loginPage("/login.html") 
  8.             .permitAll() 
  9.             .and() 
  10.             .csrf().disable() 
  11.             .sessionManagement() 
  12.             .maximumSessions(1) 
  13.             .maxSessionsPreventsLogin(true); 

添加 maxSessionsPreventsLogin 配置即可。此時(shí)一個(gè)瀏覽器登錄成功后,另外一個(gè)瀏覽器就登錄不了了。

是不是很簡(jiǎn)單?

不過(guò)還沒(méi)完,我們還需要再提供一個(gè) Bean:

 
 
 
 
  1. @Bean 
  2. HttpSessionEventPublisher httpSessionEventPublisher() { 
  3.     return new HttpSessionEventPublisher(); 

為什么要加這個(gè) Bean 呢?因?yàn)樵?Spring Security 中,它是通過(guò)監(jiān)聽(tīng) session 的銷毀事件,來(lái)及時(shí)的清理 session 的記錄。用戶從不同的瀏覽器登錄后,都會(huì)有對(duì)應(yīng)的 session,當(dāng)用戶注銷登錄之后,session 就會(huì)失效,但是默認(rèn)的失效是通過(guò)調(diào)用 StandardSession#invalidate 方法來(lái)實(shí)現(xiàn)的,這一個(gè)失效事件無(wú)法被 Spring 容器感知到,進(jìn)而導(dǎo)致當(dāng)用戶注銷登錄之后,Spring Security 沒(méi)有及時(shí)清理會(huì)話信息表,以為用戶還在線,進(jìn)而導(dǎo)致用戶無(wú)法重新登錄進(jìn)來(lái)(小伙伴們可以自行嘗試不添加上面的 Bean,然后讓用戶注銷登錄之后再重新登錄)。

為了解決這一問(wèn)題,我們提供一個(gè) HttpSessionEventPublisher ,這個(gè)類實(shí)現(xiàn)了 HttpSessionListener 接口,在該 Bean 中,可以將 session 創(chuàng)建以及銷毀的事件及時(shí)感知到,并且調(diào)用 Spring 中的事件機(jī)制將相關(guān)的創(chuàng)建和銷毀事件發(fā)布出去,進(jìn)而被 Spring Security 感知到,該類部分源碼如下:

 
 
 
 
  1. public void sessionCreated(HttpSessionEvent event) { 
  2.  HttpSessionCreatedEvent e = new HttpSessionCreatedEvent(event.getSession()); 
  3.  getContext(event.getSession().getServletContext()).publishEvent(e); 
  4. public void sessionDestroyed(HttpSessionEvent event) { 
  5.  HttpSessionDestroyedEvent e = new HttpSessionDestroyedEvent(event.getSession()); 
  6.  getContext(event.getSession().getServletContext()).publishEvent(e); 

OK,雖然多了一個(gè)配置,但是依然很簡(jiǎn)單!

3.實(shí)現(xiàn)原理

上面這個(gè)功能,在 Spring Security 中是怎么實(shí)現(xiàn)的呢?我們來(lái)稍微分析一下源碼。

首先我們知道,在用戶登錄的過(guò)程中,會(huì)經(jīng)過(guò) UsernamePasswordAuthenticationFilter,而 UsernamePasswordAuthenticationFilter 中過(guò)濾方法的調(diào)用是在 AbstractAuthenticationProcessingFilter 中觸發(fā)的,我們來(lái)看下 AbstractAuthenticationProcessingFilter#doFilter 方法的調(diào)用:

 
 
 
 
  1. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
  2.   throws IOException, ServletException { 
  3.  HttpServletRequest request = (HttpServletRequest) req; 
  4.  HttpServletResponse response = (HttpServletResponse) res; 
  5.  if (!requiresAuthentication(request, response)) { 
  6.   chain.doFilter(request, response); 
  7.   return; 
  8.  } 
  9.  Authentication authResult; 
  10.  try { 
  11.   authResult = attemptAuthentication(request, response); 
  12.   if (authResult == null) { 
  13.    return; 
  14.   } 
  15.   sessionStrategy.onAuthentication(authResult, request, response); 
  16.  } 
  17.  catch (InternalAuthenticationServiceException failed) { 
  18.   unsuccessfulAuthentication(request, response, failed); 
  19.   return; 
  20.  } 
  21.  catch (AuthenticationException failed) { 
  22.   unsuccessfulAuthentication(request, response, failed); 
  23.   return; 
  24.  } 
  25.  // Authentication success 
  26.  if (continueChainBeforeSuccessfulAuthentication) { 
  27.   chain.doFilter(request, response); 
  28.  } 
  29.  successfulAuthentication(request, response, chain, authResult); 

在這段代碼中,我們可以看到,調(diào)用 attemptAuthentication 方法走完認(rèn)證流程之后,回來(lái)之后,接下來(lái)就是調(diào)用 sessionStrategy.onAuthentication 方法,這個(gè)方法就是用來(lái)處理 session 的并發(fā)問(wèn)題的。具體在:

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

這段核心代碼我來(lái)給大家稍微解釋下:

  1. 首先調(diào)用 sessionRegistry.getAllSessions 方法獲取當(dāng)前用戶的所有 session,該方法在調(diào)用時(shí),傳遞兩個(gè)參數(shù),一個(gè)是當(dāng)前用戶的 authentication,另一個(gè)參數(shù) false 表示不包含已經(jīng)過(guò)期的 session(在用戶登錄成功后,會(huì)將用戶的 sessionid 存起來(lái),其中 key 是用戶的主體(principal),value 則是該主題對(duì)應(yīng)的 sessionid 組成的一個(gè)集合)。
  2. 接下來(lái)計(jì)算出當(dāng)前用戶已經(jīng)有幾個(gè)有效 session 了,同時(shí)獲取允許的 session 并發(fā)數(shù)。
  3. 如果當(dāng)前 session 數(shù)(sessionCount)小于 session 并發(fā)數(shù)(allowedSessions),則不做任何處理;如果 allowedSessions 的值為 -1,表示對(duì) session 數(shù)量不做任何限制。
  4. 如果當(dāng)前 session 數(shù)(sessionCount)等于 session 并發(fā)數(shù)(allowedSessions),那就先看看當(dāng)前 session 是否不為 null,并且已經(jīng)存在于 sessions 中了,如果已經(jīng)存在了,那都是自家人,不做任何處理;如果當(dāng)前 session 為 null,那么意味著將有一個(gè)新的 session 被創(chuàng)建出來(lái),屆時(shí)當(dāng)前 session 數(shù)(sessionCount)就會(huì)超過(guò) session 并發(fā)數(shù)(allowedSessions)。
  5. 如果前面的代碼中都沒(méi)能 return 掉,那么將進(jìn)入策略判斷方法 allowableSessionsExceeded 中。
  6. allowableSessionsExceeded 方法中,首先會(huì)有 exceptionIfMaximumExceeded 屬性,這就是我們?cè)?SecurityConfig 中配置的 maxSessionsPreventsLogin 的值,默認(rèn)為 false,如果為 true,就直接拋出異常,那么這次登錄就失敗了(對(duì)應(yīng) 2.2 小節(jié)的效果),如果為 false,則對(duì) sessions 按照請(qǐng)求時(shí)間進(jìn)行排序,然后再使多余的 session 過(guò)期即可(對(duì)應(yīng) 2.1 小節(jié)的效果)。

4.小結(jié)

如此,兩行簡(jiǎn)單的配置就實(shí)現(xiàn)了 Spring Security 中 session 的并發(fā)管理。是不是很簡(jiǎn)單?不過(guò)這里還有一個(gè)小小的坑,松哥將在下篇文章中繼續(xù)和大家分析。

本文案例大家可以從 GitHub 上下載:https://github.com/lenve/spring-security-samples

本文轉(zhuǎn)載自微信公眾號(hào)「江南一點(diǎn)雨」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系江南一點(diǎn)雨公眾號(hào)。

 


新聞標(biāo)題:SpringSecurity系列之只允許一臺(tái)設(shè)備在線
分享網(wǎng)址:http://www.5511xx.com/article/cdpichg.html