This will automatically update the authentication cookie once the cookie is nearing it’s expiry time. That way, if a user is on the site continuously then they will not need to re-authenticate. This is a security flaw but real world requirements sometimes mean we need to be flexible.
When ASP.Net detects the authentication cookie needs to be refreshed, it creates a new authentication cookie with a new value. Now when we check the X-XSRF-TOKEN request header value sent to us by angular as part of a POST request, the values will not match up. The user will start getting 401 exceptions after a time.
To get around this, we will need to implement the sliding exipiration functionality ourselves.
Remove the web.config slidingExpiration="true" attribute.
protectedvoidApplication_PostAuthenticateRequest(objectsender,EventArgse){varauthCookie=HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];SlidingExpirationCookie(authCookie);}privatevoidSlidingExpirationCookie(HttpCookieauthCookie){if(authCookie==null){return;}varticket=FormsAuthentication.Decrypt(authCookie.Value);varnewTicket=FormsAuthentication.RenewTicketIfOld(ticket);if(newTicket==null||newTicket.Expiration==ticket.Expiration){return;}varencryptedTicket=FormsAuthentication.Encrypt(newTicket);authCookie=newHttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket){Secure=FormsAuthentication.RequireSSL,Path=FormsAuthentication.FormsCookiePath,Domain=FormsAuthentication.CookieDomain,HttpOnly=true};if(ticket.IsPersistent){authCookie.Expires=ticket.Expiration;}Response.Cookies.Add(authCookie);varcsrfToken=newCsrfTokenHelper().GenerateCsrfTokenFromAuthToken(authCookie.Value);varcsrfCookie=newHttpCookie("FORM-XSRF",csrfToken)// remember, we don't use the default XSRF-TOKEN cookie name{HttpOnly=false,Secure=authCookie.Secure,Path=authCookie.Path,Domain=authCookie.Domain};HttpContext.Current.Response.Cookies.Add(csrfCookie);}
Now the authentication cooke and the XSRF cookie will stay in sync.