單點登陸(Single Sign On),簡稱爲 SSO,是目前比較流行的企業業務整合的解決方案之一。SSO的定義是在多個應用系統中,用戶只須要登陸一次就能夠訪問全部相互信任的應用系統。web
下面的sso是在同一個頂級域名下,多個子域。緩存
一、sso須要一個令牌,用來爲每一個站點做爲身份憑證,通常令牌用 Guid。安全
private string GetTokenValue() { return System.Guid.NewGuid().ToString(); }
private string GetTokenValue() { return System.Guid.NewGuid().ToString(); }
二、建一個passport的站點,用來作登陸驗證,登陸成功之後,生成令牌,寫入cookie的Token,並把用戶信息和Token保存在緩存中,緩能夠用System.Web.HttpRuntime.Cache,也能夠用memcache,一般用memcache,由於能夠作分佈式存儲。cookie
寫入cookie:網絡
string _token = GetTokenValue(); HttpCookie cookie = new HttpCookie("token"); cookie.Value = _token; cookie.Expires = DateTime.Now.AddDays(1); cookie.Domain = ".cc.com"; Response.Cookies.Add(cookie);
存入緩存:session
/// <summary> /// 將用戶信息保存在緩存中 /// </summary> /// <param name="user"></param> private void InsertCache(User user) { System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache; List<User> list = new List<Entity.User>(); if (cache["User"] == null) { list.Add(user); } else { list = cache["User"] as List<User>; list.Add(user); } cache.Insert("User", list, null, DateTime.MaxValue, TimeSpan.FromMinutes(double.Parse(System.Configuration.ConfigurationManager.AppSettings["Timeout"]))); }
三、第2步是直接在pssport登陸,若是是在其餘站點登陸,那麼就要先判斷是否已經登陸,這時候能夠先從cookie判斷是否存在token,若是存在,就去passport驗證是否對的token,這個怎麼驗證呢?能夠用服務遠程判斷,通常用wcf,若是成功說明已經登陸成功,就能夠把用戶信息保存在session,用session比較安全,cookis通常用來保存不是很隱密的信息。若是驗證不正確,或者cookie並不存在token,那就須要跳到passport進行登陸,而後再跳原站點。分佈式
實現代碼:ide
protected override void OnLoad(EventArgs e) { if (Request.Cookies["Token"] == null) { Response.Redirect(this.Sites.PassPortSite + "/login.aspx?gotourl=" + this.Sites.AdminSite + "/default.aspx"); } else { if (Session["member"] == null) { HttpCookie cookie = Request.Cookies["token"]; WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials;//獲取或配置用於對向Internet資源的請求進行身份驗證的網絡憑據。 string weburl = this.Sites.PassPortSite+"/gettoken.aspx?token=" + cookie.Value.ToString(); Byte[] pageData = MyWebClient.DownloadData(weburl);//從指定網站下載數據 //string pageHtml = Encoding.Default.GetString(pageData); //假如獲取網站頁面採用的是GB2312,則使用這句
//這段紅色的代碼原本應該是用服務調用的,只是爲了簡單,就直接取值了
string pageHtml = Encoding.UTF8.GetString(pageData); //假如獲取網站頁面採用的是UTF-8,則使用這句 if (!string.IsNullOrEmpty(pageHtml.Trim())) { int id = Convert.ToInt32(pageHtml); IUserBiz userBiz = new UserBiz(); Session["member"] = userBiz.GetUser(id); } else { Session["member"] = null; Response.Redirect(this.Sites.PassPortSite + "/login.aspx?gotourl="+this.Sites.AdminSite+"/default.aspx"); } } } base.OnLoad(e); }
好了,單點登陸的過程就是這樣了,但這是實現了單點登陸,還有session並無共享,如今每一個站點的session還不是同一個sessionid。網站