我有一个带有 ASP.NET 表单身份验证的网站。我最近实现了在用户登录时保存 cookie,现在我发现了一个问题。如果问题仍然存在,我不是 100%。
重现的步骤是:
- 通过 www (www.mysite.com) 访问我的网站
- 登录网站。
- 访问没有 www 的网站 (mysite.com)
- 它会要求我再次登录,所以我做到了。
- 登出网站。它将我重定向到登录页面。
- 在地址栏中输入 www.mysite.com,我发现它仍然登录。
所以访问我的网站有或没有(www)就像访问两个不同的网站一样。从 www.mysite.com 注销不会从 mysite.com 注销。登录也是如此,反之亦然。
登录页面
Login1_Authenticate Handles Login1.Authenticate
Dim result As Boolean = UserLogin(userName, password)
If (result) Then
e.Authenticated = True
If Login1.RememberMeSet = True Then
SetCookies(userName)
End If
LoginCounter(userName)
Else
e.Authenticated = False
End If
设置Cookies()
Dim tkt As FormsAuthenticationTicket
Dim cookiestr As String
Dim ck As HttpCookie
tkt = New FormsAuthenticationTicket(1, userName, DateTime.Now(), DateTime.Now.AddDays(7), False, "")
cookiestr = FormsAuthentication.Encrypt(tkt)
ck = New HttpCookie(FormsAuthentication.FormsCookieName(), cookiestr)
ck.Expires = tkt.Expiration
ck.Path = FormsAuthentication.FormsCookiePath()
HttpContext.Current.Request.Cookies.Remove(".ASPXAUTH")
Response.Cookies.Add(ck)
End Sub
母版页上的登录状态控制
LoginStatus1_LoggingOut Handles LoginStatus1.LoggingOut
FormsAuthentication.SignOut()
Session.Clear()
Session.Abandon()
Dim cookie1 As New HttpCookie(FormsAuthentication.FormsCookieName, "")
cookie1.Expires = DateTime.Now.AddYears(-1)
Response.Cookies.Add(cookie1)
Dim cookie2 As New HttpCookie("ASP.NET_SessionId", "")
cookie2.Expires = DateTime.Now.AddYears(-1)
Response.Cookies.Add(cookie2)
网页配置
<authorization>
<deny users="?"/>
</authorization>
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="Login.aspx" defaultUrl="Default.aspx" cookieless="UseCookies" timeout="1440" path="/" protection="All"/>
</authentication>
解决方案: 把它放在 Global.asax ..
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim fromurl As String = "http://mysite.com"
Dim tourl As String = "http://www.mysite.com"
If HttpContext.Current.Request.Url.ToString().ToLower().Contains(fromurl) Then
HttpContext.Current.Response.Status = "301 Moved Permanently"
HttpContext.Current.Response.AddHeader("Location", tourl)
End If
End Sub