天天看點

會話管理Session Management

HttpSessionEventPublisher

實作了HttpSessionListener接口,監聽session的建立和銷毀事件,通過ApplicationContext釋出對應的事件HttpSessionCreatedEvent  HttpSessionDestroyedEvent
//監聽session建立事件
public void sessionCreated(HttpSessionEvent event) {
    HttpSessionCreatedEvent e = new HttpSessionCreatedEvent(event.getSession());
    //釋出事件
    getContext(event.getSession().getServletContext()).publishEvent(e);
}

//監聽session銷毀事件
public void sessionDestroyed(HttpSessionEvent event) {
   HttpSessionDestroyedEvent e = new HttpSessionDestroyedEvent(event.getSession());
   //釋出事件
   getContext(event.getSession().getServletContext()).publishEvent(e);
}
           

SessionRegistry , SessionInformation

SessionInformation :記錄認證使用者的session資訊 。

lastRequest:最後一次通路次數

principal:認證使用者資訊

sessionId:session的id

expired:是否過期

SessionRegistry :

    儲存了所有認證成功後使用者的SessionInformation資訊,每次使用者通路伺服器的會從sessionRegistry中查詢出目前使用者的session資訊 ,判斷是否過期以及重新整理最後一次方法時間,預設的實作類SessionRegistryImpl,監聽了session的銷毀事件,若銷毀,那麼删除掉session資訊,有兩個屬性:

/** <principal:Object,SessionIdSet>  以認證使用者對象做key,多個sessionId 為value 。一個使用者可以對應多個不同的session,表示同一個帳号可以同時在不同的浏覽器上登入,可以配置最大允許同時登入的數*/
private final ConcurrentMap<Object,Set<String>> principals = new ConcurrentHashMap<Object,Set<String>>();
/** <sessionId:Object,SessionInformation> 以sessionid為key SessionInformation為value */
private final Map<String, SessionInformation> sessionIds = new ConcurrentHashMap<String, SessionInformation>();
           

SessionAuthenticationStrategy

void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response)  throws SessionAuthenticationException;
           

有多個實作類:

ChangeSessionIdAuthenticationStrategy:

調用HttpServletRequest的changeSessionId方法改變sessionid

SessionFixationProtectionStrategy:

首先讓原來的session過期,然後建立一個新的session,把原來session的屬性拷貝到新的session中

http://xpenxpen.iteye.com/blog/1664075

RegisterSessionAuthenticationStrategy:

使用者認證成功後sessionRegistry調用registerNewSession,儲存使用者的資訊和session

ConcurrentSessionControlAuthenticationStrategy:

允許使用者同時線上數,有一個maximumSessions屬性,預設是1。通過sessionRegistry判斷使用者數是否已經超過了最大允許數,若超過了,那麼就讓最近一個的session過期(讓上一個使用者強制下線)

CompositeSessionAuthenticationStrategy:組合使用多個SessionAuthenticationStrategy

實作控制同時線上使用者數

 1.    在web.xml中添加listener

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

 2.  在security.xml中添加代碼:

<security:http>
    <security:intercept-url pattern="/**" access="ROLE_USER"/>
    <security:form-login/>
    <security:logout logout-url="/logout"/>
    <security:session-management>
        <security:concurrency-control max-sessions="1"/>
    </security:session-management>
</security:http>
      

 預設建立的SessionAuthenticationStrategy是組合CompositeSessionAuthenticationStrategy:設定的SessionAuthenticationStrategy有:RegisterSessionAuthenticationStrategy  ConcurrentSessionControlAuthenticationStrategy  SessionFixationProtectionStrategy

繼續閱讀