跨域cookie访问
Easy Cross Domain Cookies (Sharing cookies between domains)
I own several websites that need memberships to post comments, and recently I wanted the ability to have a single login - so once the user is logged into one site they are automatically logged into the others.
Ideally, I could just write the login cookies for both domains from one location, or somehow share the same login cookie between the domains - but you quickly come up against browser security which (for good reason) doesn’t allow this sort of thing.
There are plenty of ways of solving this problem - but this is the simplest I could find. It uses an IFrame to set cookies on the foreign domain.
In the example, you have Domain A which the visitor is currently on, and Domain B, which you want to set cookies on.
Add a page ‘FrameLogin.aspx’ to your Domain B website.
Public Partial Class FrameLogin
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sUserID As String
HttpContext.Current.Response.AddHeader(”p3p”, “CP=\”"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\”"”)
sUserID = Request.QueryString(”userid”)
Dim oCookie As New HttpCookie(”UserID”)
oCookie.Value = sUserID
oCookie.Expires = DateTime.Now.AddDays(1000)
HttpContext.Current.Response.Cookies.Add(oCookie)
oCookie = Nothing
End Sub
End Class
Note that the p3p header has been added, this is to allow 3rd party cookies.
To call this page, we insert code into the appropriate ‘Login’ function in your Domain A website.
Private Function Login(ByVal sUserName As String, ByVal sPassword As String) As Boolean
Dim iUserID As Integer
iUserID = CheckLoginOKAndGetUserdID(sUserName, sPassword)
If iUserID <> 0 Then
Login = True
Response.Write(”<IFRAME style=’WIDTH:1px;HEIGHT:1px’ src=’http://www.DomainB.com/FrameLogin.aspx’ frameBorder=’0′></IFRAME>”)
Else
Login = False
End If
End Function
Once the cookie has been set on Domain B I can use it to auto-login my visitors when they get there.
Also: For simplicity, I am using an IFrame to call a page. If I wanted faster execution I could substitute an iHttpHandler for the page.
This post brought to you by WeGotDomain.com - Over 10,000 Aged domains for sale!
Related posts:
- Copying cookies across domains in ASP.Net
- We Got Domain - over 10,000 aged domains for sale
- How to set third-party cookies with iframe Facebook Applications
- Free PR2 domains (and one PR3)
- Opening a new browser window with POST data