2

FormsAuthenticationTicket从头开始创建了一个,但发现在以后检索它时,它UserData并没有回来。这是使用的代码:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        user.UserId,
                        DateTime.Now,
                        DateTime.MaxValue,
                        false,
                        user.UserType);

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);

但是,当我在 next 上重新阅读时Request,我发现该UserData字段现在是空的:

string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!

有任何想法吗?

4

3 回答 3

9

我想我找到了问题所在。如果您编写自己的 cookie 名称,它似乎没问题!所以改变:

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

HttpCookie cookie = new HttpCookie(
     "SiteCookie", 
     FormsAuthentication.Encrypt(ticket));

然后根据问题检索它:

string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works

它可能 .NET 用它做了一些棘手的事情,所以把它放在一个新的中就可以了。

更新:

此外,需要刷新票证,否则票证将在用户使用网站时过期:

FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
于 2010-09-08T15:17:56.493 回答
2

我也遇到过这个问题。但我认为真正的原因是服务器设置了两次相同的 cookie,第二次覆盖了包含您的 UserData 字段的第一个。

您可以通过 Fiddler 捕获 cookie 写入过程,这是显示此问题的屏幕截图: 在此处输入图像描述

那么,这是怎么发生的呢?在我的情况下,我使用登录控件进行身份验证。在 Login 控件的 Authenticate 事件中,我在手动检查用户名和密码后使用我的 UserData 设置 cookie。然后,我设置了AuthenticateEventArgs.Authenticated=true,此时,在调试窗口中,我看到一个新的 cookie 排队到响应中,其名称也等于 FormsAuthentication.FormsCookieName !我的解决方案是重定向到默认页面,而不是设置 AuthenticateEventArgs.Authenticated=true。

因此,您可以调试您的代码以查看身份验证 cookie 是否两次排队等待响应。

于 2012-07-12T02:27:09.737 回答
1

这对我有用:

//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);

string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);
于 2011-06-06T15:23:14.493 回答