Listing 1: Web.Config - Forms authentication configuration
To avoid logging off user even if default timeout goes by I needed to edit SignIn method from FormsAuthenticationService class which is placed in AccountController.cs file.
Listing 2: Updated SignIn method
public void SignIn(string userName, bool createPersistentCookie) { // Remember me was checked - set cookie to remember user for 10 days (or until he logs off) if (createPersistentCookie) { var tenDaysFromNow = DateTime.Now.AddDays(10); FormsAuthentication.Initialize(); HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie); cookie.Expires = tenDaysFromNow; var cookieVal = FormsAuthentication.Decrypt(cookie.Value); FormsAuthenticationTicket at = new FormsAuthenticationTicket(cookieVal.Version, cookieVal.Name, cookieVal.IssueDate, tenDaysFromNow, true, cookieVal.UserData); cookie.Value = FormsAuthentication.Encrypt(at); HttpContext.Current.Response.Cookies.Add(cookie); } else { FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } }
The code grabs default authentication cookie (line 8), decrypts its value in line 10 and based on existing value creates new Authentication Ticket with updated ExpirationDate. In the end cookie has been added to response cookies collection.
Brak komentarzy:
Prześlij komentarz