HttpCookie cookie = new HttpCookie("name", "www.Admin10000.com");
cookie.Domain = "test1.com";
cookie.Path = "/";
Response.Cookies.Add(cookie);
如果我不是二级域名而是完全在不同顶级域名中,例如 www.test1.com 所在的web应用程序创建了一个cookie,想要在 www.test2.com 或其二级域名的应用程序中访问,改怎么办呢?我们知道靠常规反的方法是访问不了的,关键我们就是看看有没有方法可以访问。事实是Cookie可以在一定条件下跨域,而不是随心所欲的实现跨域。
我们来做个测试,看看两个站点 www.test1.com 和 www.test2.com 如何实现cookie跨域访问。 按照常规我们需要有2个顶级域名,并且有DNS服务器才能够配置域名,否则我们是无法验证的,但是这里我们也没有必要那么麻烦,我们可以通过修改hosts文件来模拟。在 c:\windows\system32\drivers\etc 中有 hosts文件,在末尾添加上
其中Default.aspx是 www.test1.com 的页面,访问的地址是 http://www.test1.com/Default.aspx。看一下前台代码,它没有任何后台代码
var _frm = document.createElement("iframe");
_frm.style.display = "none";
_frm.src = "http://www.test2.com/SSO.ashx";
document.body.appendChild(_frm);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;
namespace Admin10000.Web
{
///
/// $codebehindclassname$ 的摘要说明
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SSO : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpCookie cookie = new HttpCookie("name", "www.Admin10000.com");
cookie.Domain = "test2.com";
cookie.Path = "/";
cookie.Expires = DateTime.Now.AddMinutes(10000);
context.Response.Cookies.Add(cookie);
context.Response.ContentType = "text/plain";
context.Response.AddHeader("P3P", "CP=CAO PSA OUR");
context.Response.Write("");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Admin10000.Web
{
public partial class GetCookie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["name"] != null)
{
Response.Write(Request.Cookies["name"].Value);
}
}
}
}
好了,现在我们访问测试,通过访问 http://www.test1.com/Default.aspx 之后,这时会通过iframe载入调用SSO.ashx这个页面,执行后台代码创建cookie,然后访问 http://www.test2.com/GetCookie.aspx 我们得到了相应的cookie。说明在www.test1.com下创建的cookie在www.test2.com下是可以访问到的。
通过iframe的src属性将test1.com域下的cookie值作为get参数重定向到test2.com域下SSO.ashx页面上,SSO.ashx获取test1.com域中所传过来的cookie值,并将所获取到值写入cookie中,这样就简单的实现了cookie跨域的访问。
全部评论