溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Spring Security中實(shí)現(xiàn)禁止用戶重復(fù)登陸

發(fā)布時(shí)間:2021-05-25 16:33:36 來源:億速云 閱讀:540 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)怎么在Spring Security中實(shí)現(xiàn)禁止用戶重復(fù)登陸,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

一、SpringMVC項(xiàng)目,配置如下:

首先在修改Security相關(guān)的XML,我這里是spring-security.xml,修改UsernamePasswordAuthenticationFilter相關(guān)Bean的構(gòu)造配置

加入

<property name="sessionAuthenticationStrategy" ref="sas" />

新增sas的Bean及其相關(guān)配置

<bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">
    <constructor-arg>
      <list>
        <bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
          <constructor-arg ref="sessionRegistry"/>
          <!-- 這里是配置session數(shù)量,此處為1,表示同一個(gè)用戶同時(shí)只會有一個(gè)session在線 --> 
          <property name="maximumSessions" value="1" />
          <property name="exceptionIfMaximumExceeded" value="false" />
        </bean>
        <bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy">
        </bean>
        <bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy">
          <constructor-arg ref="sessionRegistry"/>
        </bean>
      </list>
    </constructor-arg>
  </bean>

  <bean id="sessionRegistry"
        class="org.springframework.security.core.session.SessionRegistryImpl" />

加入ConcurrentSessionFilter相關(guān)Bean配置

<bean id="concurrencyFilter"
        class="org.springframework.security.web.session.ConcurrentSessionFilter">
    <constructor-arg name="sessionRegistry" ref="sessionRegistry" />
    <constructor-arg name="sessionInformationExpiredStrategy" ref="redirectSessionInformationExpiredStrategy" />
  </bean>


  <bean id="redirectSessionInformationExpiredStrategy"
        class="org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy">
    <constructor-arg name="invalidSessionUrl" value="/login.html" />
  </bean>

二、SpringBoot項(xiàng)目

三、Bean配置說明

  • SessionAuthenticationStrategy:該接口中存在onAuthentication方法用于對新登錄用戶進(jìn)行session相關(guān)的校驗(yàn)。

  • 查看UsernamePasswordAuthenticationFilter及其父類代碼,可以發(fā)現(xiàn)在doFilter中存在sessionStrategy.onAuthentication(authResult, request, response);方法

  • 但UsernamePasswordAuthenticationFilter中的sessionStrategy對象默認(rèn)為NullAuthenticatedSessionStrategy,即不對session進(jìn)行相關(guān)驗(yàn)證。

  • 如本文配置,建立id為sas的CompositeSessionAuthenticationStrategy的Bean對象。

  • CompositeSessionAuthenticationStrategy可以理解為一個(gè)托管類,托管所有實(shí)現(xiàn)SessionAuthenticationStrategy接口的對象,用來批量托管執(zhí)行onAuthentication函數(shù)

  • 這里CompositeSessionAuthenticationStrategy中注入了三個(gè)對象,關(guān)注ConcurrentSessionControlAuthenticationStrategy,它實(shí)現(xiàn)了對于session并發(fā)的控制

  • UsernamePasswordAuthenticationFilter的Bean中注入新配置的sas,用于替換原本的NullAuthenticatedSessionStrategy

  • ConcurrentSessionFilter的Bean用來驗(yàn)證session是否失效,并通過SimpleRedirectSessionInformationExpiredStrategy將失敗訪問進(jìn)行跳轉(zhuǎn)。

四、代碼流程說明(這里模擬用戶現(xiàn)在A處登錄,隨后用戶在B處登錄,之后A處再進(jìn)行操作時(shí)會返回失敗,提示重新登錄)

1、用戶在A處登錄,UsernamePasswordAuthenticationFilter調(diào)用sessionStrategy.onAuthentication進(jìn)行session驗(yàn)證

2、ConcurrentSessionControlAuthenticationStrategy中的onAuthentication開始進(jìn)行session驗(yàn)證,服務(wù)器中保存了登錄后的session

/**
   * In addition to the steps from the superclass, the sessionRegistry will be updated
   * with the new session information.
   */
  public void onAuthentication(Authentication authentication,
      HttpServletRequest request, HttpServletResponse response) {

    //根據(jù)所登錄的用戶信息,查詢相對應(yīng)的現(xiàn)存session列表
    final List<SessionInformation> sessions = sessionRegistry.getAllSessions(
        authentication.getPrincipal(), false);

    int sessionCount = sessions.size();
    //獲取session并發(fā)數(shù)量,對于XML中的maximumSessions
    int allowedSessions = getMaximumSessionsForThisUser(authentication);

    //判斷現(xiàn)有session列表數(shù)量和并發(fā)控制數(shù)間的關(guān)系
    //如果是首次登錄,根據(jù)xml配置,這里應(yīng)該是0<1,程序?qū)^續(xù)向下執(zhí)行,
    //最終執(zhí)行到SessionRegistryImpl的registerNewSession進(jìn)行新session的保存
    if (sessionCount < allowedSessions) {
      // They haven't got too many login sessions running at present
      return;
    }

    if (allowedSessions == -1) {
      // We permit unlimited logins
      return;
    }

    if (sessionCount == allowedSessions) {
      //獲取本次http請求的session
      HttpSession session = request.getSession(false);

      if (session != null) {
        // Only permit it though if this request is associated with one of the
        // already registered sessions
        for (SessionInformation si : sessions) {
          //循環(huán)已保存的session列表,判斷本次http請求session是否已經(jīng)保存
          if (si.getSessionId().equals(session.getId())) {
            //本次http請求是有效請求,返回執(zhí)行下一個(gè)filter
            return;
          }
        }
      }
      // If the session is null, a new one will be created by the parent class,
      // exceeding the allowed number
    }

    //本次http請求為新請求,進(jìn)入具體判斷
    allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);
  }
/**
   * Allows subclasses to customise behaviour when too many sessions are detected.
   *
   * @param sessions either <code>null</code> or all unexpired sessions associated with
   * the principal
   * @param allowableSessions the number of concurrent sessions the user is allowed to
   * have
   * @param registry an instance of the <code>SessionRegistry</code> for subclass use
   *
   */
  protected void allowableSessionsExceeded(List<SessionInformation> sessions,
      int allowableSessions, SessionRegistry registry)
      throws SessionAuthenticationException {
    //根據(jù)exceptionIfMaximumExceeded判斷是否要將新http請求拒絕
    //exceptionIfMaximumExceeded也可以在XML中配置
    if (exceptionIfMaximumExceeded || (sessions == null)) {
      throw new SessionAuthenticationException(messages.getMessage(
          "ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
          new Object[] { Integer.valueOf(allowableSessions) },
          "Maximum sessions of {0} for this principal exceeded"));
    }

    // Determine least recently used session, and mark it for invalidation
    SessionInformation leastRecentlyUsed = null;

    //若不拒絕新請求,遍歷現(xiàn)存seesion列表
    for (SessionInformation session : sessions) {
      //獲取上一次/已存的session信息
      if ((leastRecentlyUsed == null)
          || session.getLastRequest()
              .before(leastRecentlyUsed.getLastRequest())) {
        leastRecentlyUsed = session;
      }
    }

    //將上次session信息寫為無效(欺騙)
    leastRecentlyUsed.expireNow();
  }

3、用戶在B處登錄,再次通過ConcurrentSessionControlAuthenticationStrategy的檢查,將A處登錄的session置于無效狀態(tài),并在session列表中添加本次session

4、用戶在A處嘗試進(jìn)行其他操作,ConcurrentSessionFilter進(jìn)行Session相關(guān)的驗(yàn)證,發(fā)現(xiàn)A處用戶已經(jīng)失效,提示重新登錄

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

  //獲取本次http請求的session
    HttpSession session = request.getSession(false);
  
    if (session != null) {
      //從本地session關(guān)系表中取出本次http訪問的具體session信息
      SessionInformation info = sessionRegistry.getSessionInformation(session
          .getId());
      //如果存在信息,則繼續(xù)執(zhí)行
      if (info != null) {
        //判斷session是否已經(jīng)失效(這一步在本文4.2中被執(zhí)行)
        if (info.isExpired()) {
          // Expired - abort processing
          if (logger.isDebugEnabled()) {
            logger.debug("Requested session ID "
                + request.getRequestedSessionId() + " has expired.");
          }
          //執(zhí)行登出操作
          doLogout(request, response);

          //從XML配置中的redirectSessionInformationExpiredStrategy獲取URL重定向信息,頁面跳轉(zhuǎn)到登錄頁面
          this.sessionInformationExpiredStrategy.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));
          return;
        }
        else {
          // Non-expired - update last request date/time
          sessionRegistry.refreshLastRequest(info.getSessionId());
        }
      }
    }

    chain.doFilter(request, response);
  }

以上就是怎么在Spring Security中實(shí)現(xiàn)禁止用戶重復(fù)登陸,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI