Adsense

Saturday, January 21, 2012

FormsAuthentication.Encrypt returns null

I was refactoring some of our ASP.Net authentication code this weekend and ran into a problem when calling FormsAuthentication.Encrypt(ticket) after creating my FormsAuthenticationTicket. Calling the Encrypt method kept returning null instead of the encrypted ticket.

After a quick Google search, someone mentioned that they would also get null if their userData was null when creating their ticket. I double checked that my userData was valid and continued to scratch my head for a minute. Luckily, it was enough to set me on the right path.

It seems that FormsAuthentication. Encrypt will also return null if the name you pass into your ticket is null.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, principal.Name,	
DateTime.Now, DateTime.Now.AddMinutes(30), rememberMe, userData, FormsAuthentication.FormsCookiePath);
Essentially, the two items in red above cannot be null if you want FormsAuthentication.Encrypt to return the valid encrypted ticket. Hope this helps someone!