title: Manually renew forms authentication ticket:
body: <p>Yet another problem with forms authentication ticket expiring too soon.
  I need to use sliding Expiration set to true. I have read forums and understood the problem with the loss of precision, that the ticket only gets updated if the request is made after half of the expiration time only.</p>
  
  <p>The problem:
  In my webconfig I have as follows:</p>
  
  <pre><code>    &lt;authentication mode="Forms"&gt;
          &lt;forms timeout="20" name="SqlAuthCookie" protection="All" slidingExpiration="true" /&gt;
      &lt;/authentication&gt;
      &lt;sessionState timeout="20" /&gt;
      &lt;authorization&gt;
  </code></pre>
  
  <p>The user must only be logged out and redirected to login.aspx, only when there was no request made in the 20 Minute interval. The problem is that users are making requests, and still get thrown to the login page. This should not happen. What I thought of doing, was to reset the SqlAuthCookie manually for each request. </p>
  
  <p>Below is my code. It is called on context.AcquireRequestState.</p>
  
  <pre><code>    void context_AcquireRequestState(object sender, EventArgs e)
      {
          HttpContext ctx = HttpContext.Current;
          ResetAuthCookie(ctx);
       }
  
              private void ResetAuthCookie(HttpContext ctx)
      {
          HttpCookie authCookie = ctx.Request.Cookies[FormsAuthentication.FormsCookieName];
          if (authCookie == null)
              return;
  
          FormsAuthenticationTicket ticketOld = FormsAuthentication.Decrypt(authCookie.Value);
          if (ticketOld == null)
              return;
  
          if (ticketOld.Expired)
              return;
  
          FormsAuthenticationTicket ticketNew = null;
          if (FormsAuthentication.SlidingExpiration)
             ticketNew = FormsAuthentication.RenewTicketIfOld(ticketOld);
  
          if (ticketNew != ticketOld)
              StoreNewCookie(ticketNew, authCookie, ctx);
      }
  
      private void StoreNewCookie(FormsAuthenticationTicket ticketNew, HttpCookie authCookie, HttpContext ctx)
      {
          string hash = FormsAuthentication.Encrypt(ticketNew);
          if (ticketNew.IsPersistent)
              authCookie.Expires = ticketNew.Expiration;
  
          authCookie.Value = hash;
          authCookie.HttpOnly = true;
  
          ctx.Response.Cookies.Add(authCookie);
      }
  </code></pre>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Is it wrong or an acceptable solution, resetting the cookie on each request?</li>
  <li>Why does it still not work? It seems that new Ticket never gets renewed.</li>
  <li>Are there other causes possible, for the fact that the users have their forms authentication expired too soon, that I should investigate? </li>
  </ol>
  
  <p>Thank you,
  Regards,</p>