ASP.MVC Remember me cookie not working after session time out

1.9k views Asked by At

On a login form I have an option to allow the user to click a remember me checkbox which creates a new FormsAuthenticationTicket which then gets added to a cookie.

if (_model.RememberMe)
{

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                      _model.Username,
                                      DateTime.Now,
                                      DateTime.Now.AddDays(30),
                                      true,
                                      _model.Username,
                                      FormsAuthentication.FormsCookiePath);

    // Encrypt the ticket.
    string encTicket = FormsAuthentication.Encrypt(ticket);

    // Create the cookie.
    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

Which should hopefully be in the clients browser for 30 days as stated above.

Testing this, I've purposely left the current session timeout for only a minute

<sessionState timeout="1"></sessionState>

So after a minute, if the user has said "remember me" I expect the website should not be redirected back to the login page. However it does. This is the code that does it.

        // [".ASPXAUTH"] is the cookie name that is created by the FormsAuthenticationTicket`
        if (User.Identity.Name == "" && Request.Cookies[".ASPXAUTH"] == null)
        {

            return RedirectToAction("LogOut", "Login");
        }


        // the current session hasn't timed out or the remember me cookie is enabled
        FormsIdentity id = (FormsIdentity)User.Identity;
        FormsAuthenticationTicket ticket = id.Ticket;

But the cookie is NULL.

I am expecting it's a misunderstanding on my behalf so if anyone can give me a hand. I would be very grateful.

Thanks

1

There are 1 answers

4
Mō Iđɍɨɇƶ On

What you are looking for is

string mySessionCookie = System.Web.HttpContext.Current.Request.Headers["Cookie"];
if (mySessionCookie.IndexOf(".ASPXAUTH", StringComparison.Ordinal) >= 0) {
    // do something
}

EDIT

How about this, I haven't tested it but I remember doing something like this before

HttpCookie cookie = (HttpCookie)(Request.Cookies[FormsAuthentication.FormsCookieName]);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);