title: How to intercept 401 from Forms Authentication in ASP.NET MVC?
body: <p>I would like to generate a 401 page if the user does not have the right permission.</p>
  
  <p>The user requests a url and is redirected to the login page (I have deny all anonymous in web.config).  The user logs in successfully and is redirected to the original url.  However, upon permission check, it is determined that the user does not have the required permission, so I would like to generate a 401.  But Forms Authentication always handles 401 and redirects the user to the login page.</p>
  
  <p>To me, this isn't correct.  The user has already <strong>authenticated</strong>, the user just does not have the proper <strong>authorization</strong>.</p>
  
  <p>In other scenarios, such as in ajax or REST service scenario, I definitely do not want the login page - I need the proper 401 page.</p>
  
  <p>So far, I've tried custom Authorize filter to return ViewResult with 401 but didn't work.  I then tried a normal Action Filter, overriding OnActionExecuting, which did not work either.</p>
  
  <p>What I was able to do is handle an event in global.asax, PostRequestHandlerExecute, and check for the permission then write out directly to response:</p>
  
  <pre><code>if (permissionDenied)
  {
      Context.Response.StatusCode = 401;
      Context.Response.Clear();
      Context.Response.Write("Permission Denied");
      Context.Response.Flush();
      Context.Response.Close();
      return;
  }
  </code></pre>
  
  <p>That works but it's not really what I want.
  First of all, I'm not even sure if that is the right event or the place in the pipeline to do that.
  Second, I want the 401 page to have a little more content.  Preferably, it should be an aspx page with possibly the same master page as the rest of the site.  That way, anyone browsing the site can see that the permission is denied but with the same look and feel, etc. but the ajax or service user will get the proper status code to act on.</p>
  
  <p>Any idea how this can be achieved?
  I've seen other posts with similar requests but didn't see a solution that I can use.</p>
  
  <p>And no, I do not want a 403.</p>