.net 实现Cookie跨域共享,单点登录SSO
实现原理:cookie是不能跨域访问的,但是在二级域名是可以共享cookie的
概念说明:站点1=a.devin.com 站点2=b.devin.com
实现步骤:1. 配置两个站点的webconfig
2. a.devin.com写入cookie
3. b.devin.com读取cookie
一、配置Webconfig:
<authentication mode="Forms">
<forms domain="devin.com" name="devin.authcookie" protection="All" />
</authentication>
<machineKey validationKey="0FA0557BB72D5E7ADD89A4B4FD40E3E232D17EFE06874FA8DD358D5484B8A4C5E1D3629B79FFD3D6D53184495CAED1164BCC1F19B47B89B7CA35875B4A687FAE" decryptionKey="A4BBD94822A8731F" validation="SHA1" />
以上machineKey自行生成配置;
如下是登陆写入cookie代码
1 /// <summary> 2 /// 登陆验证成功后写入FormsAuthenticationTicket 3 /// </summary> 4 /// <param name="userCode">登录名</param> 5 /// <param name="userData">登陆用户信息</param> 6 /// <param name="isAutoLogin">是否自动登陆</param> 7 public static void Login(string userCode, string userData, bool isAutoLogin = false) 8 { 9 FormsAuthentication.Initialize(); 10 DateTime expirationTime = DateTime.Now.AddMinutes(60); 11 if (isAutoLogin) expirationTime = DateTime.Now.AddDays(7); 12 var authTicket = new FormsAuthenticationTicket(1, userCode, DateTime.Now, expirationTime, false, userData, FormsAuthentication.FormsCookiePath); 13 var encryptedTicket = FormsAuthentication.Encrypt(authTicket); 14 var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) 15 { 16 Domain = FormsAuthentication.CookieDomain, 17 Path = FormsAuthentication.FormsCookiePath, 18 Expires = expirationTime, 19 HttpOnly = true 20 }; 21 HttpContext.Current.Response.Cookies.Add(authCookie); 22 }
以下是读取登陆cookie信息代码(LoginedUserInfo为登陆用户实体对象,自定义,与登陆中的userData的json串相对应序列化)
1 /// <summary> 2 /// 获取当前登录用户信息,如未登陆则返回NULL 3 /// </summary> 4 /// <returns>返回当前登录用户信息</returns> 5 public static LoginedUserInfo GetLoginInfo() 6 { 7 var currentuser = HttpContext.Current.User; 8 if (!currentuser.Identity.IsAuthenticated) return null; 9 var userData = ((FormsIdentity)currentuser.Identity).Ticket.UserData; 10 if (string.IsNullOrWhiteSpace(userData)) return null; 11 LoginedUserInfo loginMember = SerializationHelper.JsonDeserialize<LoginedUserInfo>(userData); 12 return loginMember; 13 }