title: Re-authenticate User in MVC application for Action
body: <p>How do I force a user to reauthenticate before performing an Action in MVC? </p>
  
  <p>We're using Windows authentication. There are some actions that we want to make sure are being performed by the user (and prevent other users from performing those actions if the user forgot to lock their workstation).</p>
  
  <p>Ideally I'd just be able to write an attribute that extends <code>Authorize</code>:</p>
  
  <pre><code>namespace AuthTest.Controllers
  {
      [Authorize(Roles="MyApp")]
      public class HomeController : Controller
      {    
          public ActionResult Index()
          {
               // A regular action
              return View();
          } 
  
          [ReAuthenticate]
          public ActionResult CriticalAction()
          {
              // Do something important
              return View();
          }
       }
  }
  </code></pre>
  
  <p>It appears that I can force the user to re-enter their credentials by having the custom <code>ReAuthenticate</code> attribute issue a <code>HTTP 401</code> response in the <code>AuthorizeCore</code> method. However, this required some trickery since <code>Html.ActionLink</code> was sending two requests:</p>
  
  <pre><code>protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
      bool ok = base.AuthorizeCore(httpContext);
      if (!ok) return false;
  
      if (httpContext.Session["ReAuthCnt"] == null)
      {
          httpContext.Session["ReAuthCnt"] = 1;
          return false;
      }
      else if ((int) httpContext.Session["ReAuthCnt"] &lt; 2)
      {
          httpContext.Session["ReAuthCnt"] = (int)httpContext.Session["ReAuthCnt"] + 1;
          return false;
      }
      else
      {
          httpContext.Session["ReAuthCnt"]  = 0;
          return true;
      }
  }
  </code></pre>
  
  <p>Is there a better way to accomplish the re-authorization? </p>