Monday, September 3, 2018

FormsAuthenticationTicket: how to keep the user logged in after the browser has been closed?

Leave a Comment

I'm logging the user this way, using FormsAuthenticationTicket:

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(LoginViewModel loginView) {     if (ModelState.IsValid)     {         if (Membership.ValidateUser(loginView.Email, loginView.Password))         {             var user = (CustomMembershipUser)Membership.GetUser(loginView.Email, false);             if (user != null)             {                 CustomPrincipalSerializeModel userSerializeModel = new CustomPrincipalSerializeModel()                 {                     ID = user.ID,                     FirstName = user.FirstName,                     LastName = user.LastName,                     RoleName = user.Roles.Select(r => r.RoleName).ToList()                 };                  string userData = JsonConvert.SerializeObject(userSerializeModel);                 DateTime expirationDate = loginView.KeepMeLoggedIn ? DateTime.Now.AddMonths(12) : DateTime.Now.AddMinutes(15);                 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, expirationDate, false, userData);                  HttpCookie faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket));                 Response.Cookies.Add(faCookie);             }              return RedirectToAction("Index", "Home");         }     }      ModelState.AddModelError("", "Login Error");      return View("Login"); } 

But even if I set loginView.KeepMeLoggedIn to true (which should keep the login for 1 year), when I close the browser and I reopen the website, the user is logged off.

How can I keep it logged in also when I close the browser?

1 Answers

Answers 1

First, you need to set the 5th parameter of the FormsAuthenticationTicket constructor 'isPersistent' to true.

Then I would add change the code to this:

var faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket)); if (authTicket.IsPersistent) {     faCookie.Expires = authTicket.Expiration; } Response.Cookies.Add(faCookie); 

And if you also want to honor what's configured in web.config, you can add this extra code (optional):

var faCookie= new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); faCookie.Path = FormsAuthentication.FormsCookiePath;  if (FormsAuthentication.RequireSSL) {     faCookie.Secure = true; }  if (FormsAuthentication.CookieDomain != null) {     faCookie.Domain = FormsAuthentication.CookieDomain; } ... 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment