Mustafakidd Mustafakidd - 2 months ago 23
ASP.NET (C#) Question

System.Web.Security.FormsAuthentication.Encrypt returns null

I'm trying to encrypt some userData to create my own custom IPrincipal and IIdentity objects using Forms authentication - I've serialized an object representing my logged in user to Json and created my FormsAuthentication ticket like so:

string user_item = GetJsonOfLoggedinUser();/*get JSON representation of my logged in user*/

System.Web.Security.FormsAuthenticationTicket ticket =
new System.Web.Security.FormsAuthenticationTicket(1,
WAM.Utilities.SessionHelper.LoggedInEmployee.F_NAME + " "
+ WAM.Utilities.SessionHelper.LoggedInEmployee.L_NAME,
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);

Response.Cookies.Add(auth_cookie);


However, the string
encrypted_ticket
is always
null
. Is there a limit on the length of the
user_item
string?

Thanks
Mustafa

Answer

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.