UserData property of FormsAuthenticationTicket is empty despite being set

混江龙づ霸主 提交于 2019-12-23 08:53:50

问题


For some reason, I the UserData property of my authentication cookie is empty. Here is the code:

var authCookie = FormsAuthentication.GetAuthCookie(userName, rememberUser.Checked);
// Get the FormsAuthenticationTicket out of the encrypted cookie
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
// Create a new FormsAuthenticationTicket that includes our custom User Data
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "userData");
// Update the authCookie's Value to use the encrypted version of newTicket
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
// Manually add the authCookie to the Cookies collection
Response.Cookies.Add(authCookie);
FormsAuthentication.RedirectFromLoginPage(userName, rememberUser.Checked);

Here is how I try to access it:

if (HttpContext.Current.Request.IsAuthenticated )
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        string data = authTicket.UserData;
        // data is empty !!!
    }
}

回答1:


RedictFromLoginPage overwrites your cookie. Remove this line and redirect manually (Response.Redirect).




回答2:


This is a similar answer I answered few days ago.

https://stackoverflow.com/a/16365000/296861

You cannot use FormsAuthentication.SetAuthCookie or FormsAuthentication.RedirectFromLoginPage if you create FormsAuthenticationTicket by yourself.




回答3:


it seems to me you were doing the same tutorial... i have encountered the same problem in my case .. it was a web config error..

 <authentication mode="Forms">
    <forms slidingExpiration="true" timeout="60" cookieless="UseUri"/>
  </authentication>

if you have cookieless="UseUri" in your web config remove it.. it work in my case



来源:https://stackoverflow.com/questions/16594905/userdata-property-of-formsauthenticationticket-is-empty-despite-being-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!