Search code examples
c#session-cookiesforms-authenticationutchttpcookie

Wrong date in HttpCookie sending to browser


I am having a problem while sending a HttpCookie expiration to the browser, I am setting it with DateTime.Now but in various browsers a different value is appearing.

Here is the code and what appears in the browser.

PS: I have tested the following browsers (Chrome, Firefox and Edge) and the same problem occurs.

var expiration = DateTime.Now.AddMinutes(30);
var authTicket = new FormsAuthenticationTicket(1, usr.Id.ToString(), DateTime.Today, expiration, true, string.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
   Secure = Request.RequireSSL(),
   Path = FormsAuthentication.FormsCookiePath,
   Domain = FormsAuthentication.CookieDomain,
   Expires = authTicket.Expiration
 };

 Response.Cookies.Add(cookie);

Cookie in browser

Debugging the expiration time


Solution

  • please observe your code below:

    var authTicket = new FormsAuthenticationTicket(1, usr.Id.ToString(), DateTime.Today, expiration, true, string.Empty);
    

    On third parameter you are using DateTime.Today and the rigth way is to use DateTime.Now.

    This should be the right code:

    var authTicket = new FormsAuthenticationTicket(1, usr.Id.ToString(), DateTime.Now, expiration, true, string.Empty);
    

    Please let me know if it works for you. Regards.