views:

91

answers:

2

Hi

I have my own asp.net cookie here made like this

   FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(version,userName,DateTime.UtcNow,DateTime.UtcNow.AddMinutes(30),createPersistentCookie,userData,"/");
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

Ass you can see I everything is in UTC time.

When I do decryption on it.

   var cookie =HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (cookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                return ticket.Expiration.Ticks;
            }
            else
            {
                return 0;
            }

It is local time. So does it convert it automatically or something? If so how can I get it back to UTC time?

+2  A: 

From MSDN:

FormsAuthenticationTicket.Expiration Property

Gets the local date and time at which the forms-authentication ticket expires.

You can use the DateTime.ToUniversalTime method to convert a DateTime to UTC:

return ticket.Expiration.ToUniversalTime().Ticks;
dtb
A: 

As you've seen, once the FormsAuthenticationTicket has been serialized to a cookie and deserialized, the Expiration and Issue times will always be local.

The Remarks section in MSDN says "If the FormsAuthenticationTicket was created using a constructor that takes an expiration parameter, the Expiration property returns the value supplied to the expiration parameter.". Hence if you pass UTC, you will get back UTC until the ticket has been serialized/deserialized, after which it will be converted to local.

If you supply issueDate and expiration to the constructor, they should normally be in local time. However no attempt is made to convert them to local time - probably the reason for this is for backwards compatibility with .NET 1.x.

With .NET 1.x the DateTime struct did not have a "Kind" property, so there was no way to tell it the caller supplied UTC or local time - it was just assumed to be local.

Therefore I suggest you change your code to pass local time to the FormsAuthenticationTicket constructor, though it does expose you to this bug recorded on Microsoft Connect.

Joe
Hmm. But local time would be of the server time. Would it not be better still pass the UTC time?. I did what dtb and convert it back to UTC time even though I guess it would make no difference.
chobo2