System.Web.Security.FormsAuthentication.Encrypt returns null

↘锁芯ラ 提交于 2019-12-05 01:17:49

Yes, the typical cookie limit is ~4k.

Add encryption and you are down to <2k.

Your code is correct.. consider:

string user_item = "fsddfdfssdfsfdasdfsf";

System.Web.Security.FormsAuthenticationTicket ticket =
    new System.Web.Security.FormsAuthenticationTicket(1,
     " sdfasdf asdflasdfasd ",
    DateTime.Now, DateTime.Now.AddMinutes(30), false, user_item);

string encrypted_ticket = 
    System.Web.Security.FormsAuthentication.Encrypt(ticket);

HttpCookie auth_cookie = 
    new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encrypted_ticket);

Yields:

95ED981CFDF6AE506650E2AD01D2B52666AFC4895F0E19F14D82628C3F263EF1DA77F73BFD0284BEDCF815FBFB9AF00AF8875C61D01E27BF53C229F19C7CDE54FBC10AC478FAF02237DDC545AEF32BBA8EED88DBB09D671CD87E685E9FE05908CAE02EB05880DC1D230D67AEB0D7B0F258435D906EBD7F505DCCD738D94532E96363B13DA92060720476619672FEC670

While it is my experience that bloated cookies are truncated as opposed to nulled, your issue is probably that JSON contains characters that will make your cookie malformed, thus breaking it.

Make sure your json is a reasonable size, then try

string user_item = Server.UrlEncode(GetJsonOfLoggedinUser());

Make sure you measure your cookies and don't try to push it, it will bite in subtle and vicious ways when you want to be home watching Lost and drinking tequila. no fun.

As an addition to this issue, when the userData parameter is null the encrypted_ticket will also be null.

In this example:

var ticket = new System.Web.Security.FormsAuthenticationTicket(1,
         "username",
        DateTime.Now, DateTime.Now.AddMinutes(30), false, null);

string encrypted_ticket = System.Web.Security.FormsAuthentication.Encrypt(ticket);

encrypted_ticket yields now null. However when using an empty string or string.Empty for the userData parameter we get a valid encrypted_ticket.

This is also somewhat documented on MSDN

Note

The userData parameter cannot be null.

Siroos Asadi

i used this code to redirect from login page to may deafault.aspx page and my UserData was Null like your Problem:

FormsAuthentication.RedirectFromLoginPage(username, false);

i change the code , try this code to redirect from Login.aspx to Default.aspx page and your User Data will be fine:

Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName, false));

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