最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Security實現(xiàn)禁止用戶重復(fù)登陸的配置原理

 更新時間:2019年12月11日 15:11:01   作者:二刀  
這篇文章主要介紹了Spring Security實現(xiàn)禁止用戶重復(fù)登陸的配置原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

這篇文章主要介紹了Spring Security實現(xiàn)禁止用戶重復(fù)登陸的配置原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

系統(tǒng)使用了Spring Security做權(quán)限管理,現(xiàn)在對于系統(tǒng)的用戶,需要改動配置,實現(xiàn)無法多地登陸。

一、SpringMVC項目,配置如下:

首先在修改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,表示同一個用戶同時只會有一個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項目

三、Bean配置說明

  • SessionAuthenticationStrategy:該接口中存在onAuthentication方法用于對新登錄用戶進(jìn)行session相關(guān)的校驗。
  • 查看UsernamePasswordAuthenticationFilter及其父類代碼,可以發(fā)現(xiàn)在doFilter中存在sessionStrategy.onAuthentication(authResult, request, response);方法
  • 但UsernamePasswordAuthenticationFilter中的sessionStrategy對象默認(rèn)為NullAuthenticatedSessionStrategy,即不對session進(jìn)行相關(guān)驗證。
  • 如本文配置,建立id為sas的CompositeSessionAuthenticationStrategy的Bean對象。
  • CompositeSessionAuthenticationStrategy可以理解為一個托管類,托管所有實現(xiàn)SessionAuthenticationStrategy接口的對象,用來批量托管執(zhí)行onAuthentication函數(shù)
  • 這里CompositeSessionAuthenticationStrategy中注入了三個對象,關(guān)注ConcurrentSessionControlAuthenticationStrategy,它實現(xiàn)了對于session并發(fā)的控制
  • UsernamePasswordAuthenticationFilter的Bean中注入新配置的sas,用于替換原本的NullAuthenticatedSessionStrategy
  • ConcurrentSessionFilter的Bean用來驗證session是否失效,并通過SimpleRedirectSessionInformationExpiredStrategy將失敗訪問進(jìn)行跳轉(zhuǎn)。

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

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

2、ConcurrentSessionControlAuthenticationStrategy中的onAuthentication開始進(jìn)行session驗證,服務(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í)行下一個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)的驗證,發(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);
  }

5、A處用戶只能再次登錄,這時B處用戶session將會失效重登,如此循環(huán)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java使用FastJson解析Json數(shù)據(jù)

    java使用FastJson解析Json數(shù)據(jù)

    本篇文章主要介紹了java使用FastJson解析Json數(shù)據(jù),fastjson 是一個性能極好的用 Java 語言實現(xiàn)的 JSON 解析器和生成器,有興趣的可以了解一下。
    2017-02-02
  • SpringBoot接收form-data和x-www-form-urlencoded數(shù)據(jù)的方法

    SpringBoot接收form-data和x-www-form-urlencoded數(shù)據(jù)的方法

    form-data和x-www-form-urlencoded是兩種不同的HTTP請求體格式,本文主要介紹了SpringBoot接收form-data和x-www-form-urlencoded數(shù)據(jù)的方法,具有一定的參考價值,感興趣的可以了解一下
    2024-05-05
  • SpringMVC實現(xiàn)數(shù)據(jù)綁定及表單標(biāo)簽

    SpringMVC實現(xiàn)數(shù)據(jù)綁定及表單標(biāo)簽

    這篇文章主要為大家詳細(xì)介紹了SpringMVC實現(xiàn)數(shù)據(jù)綁定及表單標(biāo)簽的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-03-03
  • LongAdder原理及創(chuàng)建使用示例詳解

    LongAdder原理及創(chuàng)建使用示例詳解

    這篇文章主要為大家介紹了LongAdder原理及創(chuàng)建使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01
  • Mybatis 簡介與原理

    Mybatis 簡介與原理

    MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的持久層框架。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集
    2017-05-05
  • MybatisPlus條件查詢的具體使用

    MybatisPlus條件查詢的具體使用

    MybatisPlus通過條件構(gòu)造器可以組裝復(fù)雜的查詢條件,本文主要介紹了MybatisPlus條件查詢的具體使用,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • java中forward轉(zhuǎn)發(fā)的使用

    java中forward轉(zhuǎn)發(fā)的使用

    在Java中,forward轉(zhuǎn)發(fā)是一種非常常見且重要的操作,我們將深入探討forward的概念和用法,并給出一些代碼示例來幫助讀者更好地理解,感興趣的可以了解下
    2023-11-11
  • 淺談Java 中的單元測試

    淺談Java 中的單元測試

    這篇文章主要介紹了Java 中的單元測試的相關(guān)資料,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2020-09-09
  • IDEA2023.3.4開啟SpringBoot項目的熱部署(圖文)

    IDEA2023.3.4開啟SpringBoot項目的熱部署(圖文)

    本文使用的開發(fā)工具是idea,使用的是springboot框架開發(fā)的項目,配置熱部署,可以提高開發(fā)效率,文中通過圖文介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • Jersey框架的統(tǒng)一異常處理機(jī)制分析

    Jersey框架的統(tǒng)一異常處理機(jī)制分析

    初學(xué)者往往不清楚java的異常為什么會設(shè)計成這個樣子,他們通常會對異常只進(jìn)行簡單的處理
    2016-07-07

最新評論

德庆县| 达州市| 斗六市| 衡山县| 太仆寺旗| 武鸣县| 中阳县| 蕲春县| 墨脱县| 蕲春县| 扶沟县| 财经| 丁青县| 社会| 平顶山市| 南漳县| 泸定县| 浮山县| 江北区| 丰都县| 新乐市| 江津市| 洛隆县| 翼城县| 丹寨县| 乌拉特前旗| 大厂| 仙居县| 南漳县| 浙江省| 深圳市| 萍乡市| 丰城市| 斗六市| 聂拉木县| 申扎县| 郸城县| 扎赉特旗| 庄浪县| 汶川县| 融水|