实现原理:cookie是不能跨域访问的,但是在二级域名是可以共享cookie的
概念说明:站点1=a.abc.com 站点2=b.abc.com
实现步骤:1. 配置两个站点的webconfig
2. a.abc.com写入cookie
3. b.abc.com读取cookie
一、配置Webconfig:
<httpRuntime targetFramework="4.0" />
我用的vs2012,默认生成的targetFramework=4.5 不知道为什么 4.5就不能跨域,有知道的朋友请指教。
<authentication mode="Forms">
<forms domain="abc.com" name="abc.authcookie" protection="None" />
</authentication>
测试了N久,这三个属性少一个都不能访问。两个站点的authentication配置是一样的。
二、站点1写入cookie
//利用asp.net中的form验证加密数据,写入Cookie
private HttpCookie GetAuthCookie(string userData, string userName)
{
//登录票证
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
3,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(100000),
false,
userData,
FormsAuthentication.FormsCookiePath //可在webconfig中设置 默认为/
);
string encTicket = FormsAuthentication.Encrypt(ticket);
if ((encTicket == null) || (encTicket.Length < 1))
{
throw new HttpException("Unable_to_encrypt_cookie_ticket");
}
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Path = "/";
cookie.HttpOnly = true; //是否可通过脚本访问 设置为true 则不可通过脚本访问
cookie.Domain = FormsAuthentication.CookieDomain; //webconfig中设置的domain
//cookie.Secure = FormsAuthentication.RequireSSL; //当此属性为 true 时,该 Cookie 只能通过 https:// 请求来发送
if (ticket.IsPersistent) //票证是否持久存储
{
cookie.Expires = ticket.Expiration;
}
return cookie;
}
三、站点2读取cookie
T user=null;
if (HttpContext.User != null
&& HttpContext.User.Identity.IsAuthenticated
&& HttpContext.User.Identity.Name != string.Empty
&& HttpContext.User.Identity.AuthenticationType == "Forms")
{
FormsIdentity id = HttpContext.User.Identity as FormsIdentity;
if (id != null)
{
FormsAuthenticationTicket ticket = id.Ticket;
user = this.DeserializeUserInfo(ticket.UserData);
if (user == null)
{
return false;
}
return true;
}
else
{
user = default(user);
return false;
}
}
else
{
user = default(user);
return false;
}