如果要實現單點登錄,統一的認證系統是SSO的前提之一。簡單說說單用戶登錄。怎么在同一個賬號的下,后一個登錄的把前一個踢掉
方法一:
1.在web.config文件的system.web 結點加<sessionState mode="InProc"></sessionState>這樣可以觸發global.asax文件中的session_end事件
2.global.asax文件,Session_End 事件,在Application存儲驗證字段online
Hashtable hash = (Hashtable)Application["online"]; if (hash[Session.SessionID] != null){ hash.Remove(Session.SessionID); } Application["online"] = hash;
3.登錄的時候,給online賦值,記錄用戶id,登錄ip,登錄時間等信息,如果用戶id相同就更新online的值
private void isLogin() { Hashtable h = (Hashtable)Application["online"]; if (h == null) { h = new Hashtable(); } //驗證用戶是否在Application中存在(是否在線) IDictionaryEnumerator e1 = h.GetEnumerator(); while (e1.MoveNext()) { if (checkCookie(e1.Value.ToString())) { h.Remove(e1.Key); break; } } //生成服務端標識值 DateTime now = DateTime.Now; string cookieValue = now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString(); //把userid + 標識值寫入全局變量表 h[Session.SessionID] = _user.Guid.Trim() + "," + cookieValue; Application["Online"] = h;
//把標識值寫入客戶端cookie
Response.Cookies["hqs"].Value = cookieValue;
Response.Cookies["hqs"].Expires = DateTime.Now.AddDays(1);
Session[System.Web.Configuration.WebConfigurationManager.AppSettings["LOGIN_USER"]] = _user.Guid; }
4.當用戶請求帶有Session頁面的,獲取Session和Application,和本地存儲的密鑰對比,如果不相同就結束當前用戶的會話,這樣就可以實現單用戶登錄
Object obj = Session[System.Web.Configuration.WebConfigurationManager.AppSettings["LOGIN_USER"]]; if (obj == null) { //session為空,轉重新登錄頁面 Response.Redirect(this.RootPath + this._redirect_url); } //如果會話中的標識不相同,就是賬號在其他地方登錄,結束會話 Hashtable h = (Hashtable)Application["online"]; if (h == null) { h = new Hashtable(); } IDictionaryEnumerator e1 = h.GetEnumerator(); while (e1.MoveNext()) { if (Request.Cookies["hqs"] != null) { string cookieValue = Request.Cookies["hqs"].Value; char[] sp = new char[1] { ',' }; string LoginUserid = e1.Value.ToString().Split(sp)[0].ToString(); string LoginCookie = e1.Value.ToString().Split(sp)[1].ToString(); if (LoginUserid == Convert.ToString(obj) && LoginCookie != cookieValue) { Session.RemoveAll(); //結束會話,轉重新登錄頁面 Response.Redirect(this.RootPath + this._redirect_url); } } }