0

Here my cookie create code: This is controller (model.RememberMe is a checkbox value)

int timeout = (model.RememberMe) ? (int) FormsAuthentication.Timeout.TotalMinutes : Session.Timeout;//4h
                    HttpCookie cookie = accountService.GetCookie(userId, model.RememberMe, timeout);
                    Response.Cookies.Add(cookie);
                    Logger.Debug("POST: AccountController LogOn end.");
                    result = returnUrl != null
                        ? RedirectToLocal(returnUrl)
                        : RedirectToAction("Index", "Profile", new {id = userId});

Service method that's create cookie

public HttpCookie GetCookie(int userId, bool rememberMe, int timeout)
        {
            Logger.Trace("AccountService GetCookie start with arguments:" +
                         " userId = {0}, rememberMe = {1}.", userId, rememberMe);
            var authTicket = new FormsAuthenticationTicket(
                               1,
                               Convert.ToString(userId),
                               DateTime.Now,
                               DateTime.Now.AddMinutes(timeout),
                               rememberMe,
                               string.Empty,
                               "/"
                               );
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                FormsAuthentication.Encrypt(authTicket));
            Logger.Debug("Cookie for user with userId = {0} has created", userId);
            Logger.Trace("AccountService GetCookie end.");
            return cookie;
        }

But unfortunately RememberMe dont work and cookies expires at the end of the browser session.Why?

What is the purpose of FormsAuthenticationTicket isPersistent property? Here some kind of answer but i dont understand why it doesnt work?

Community
  • 1
  • 1
Anton Kozlovsky
  • 203
  • 1
  • 15

1 Answers1

0

The difference between your code and the SO answer that you linked is that they use:

FormsAuthentication.SetAuthCookie(model.UserName, true);

Which makes the cookie with proper expiration time based on the IsPersistent property. However, if you return the cookie with the constructor like in your code:

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));

Then the expiration time will be set to browser-session because that is the default behavior of the HttpCookie class: what is the default expiration time of a cookie

So you probably have two options. Use the FormsAuthentication.SetAuthCookie method outlined in the answer you linked to, or add:

cookie.Expires = DateTime.Now.AddMinutes(10); // or whatever you want

Community
  • 1
  • 1
welegan
  • 3,013
  • 3
  • 15
  • 20