我创建了一个 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);

但是,在下一个阅读本文时 Request, ,我发现 UserData 字段现在为空:

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

有任何想法吗?

有帮助吗?

解决方案

我想我发现了这个问题。如果您编造自己的饼干名称,似乎很好!因此,从:

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

其他提示

这对我有用:

//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);

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

您可以捕获Fiddler的Cookie写作过程,这是一个显示此问题的屏幕截图:enter image description here

那么,这是怎么发生的?在我的情况下,我使用登录控件进行身份验证。在登录控件的身份验证事件中,在检查用户名和密码后,我将cookie与我的用户达到。然后,我设置了 AuthenticateEventArgs.Authenticated=true, ,目前,在调试窗口中,我看到一个新的cookie排队为响应,名称也等于formauthentication.formscookiename!我的解决方案是重定向到默认页面,而不是设置AuthenticateEventArgs.authenticatienationed = true。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top