title: Redirect unauthorized users asp net
body: <p>I'm working on a simple website in asp.net.
  I would like to restric access to the side, so that only users in a specific AD group is allowed. I have done that and it is working fine. But when a user that's not in the AD group tries to access the site, they are getting a login prompt. How do I redirect the unauthorized user to a custom page, instead of they getting the login prompt?</p>
  
  <p>Below is my web.config. The lowest part of the code, is something i tried but did not work.</p>
  
  <pre><code>&lt;configuration&gt;
  &lt;system.web&gt;
    &lt;compilation debug="true" targetFramework="4.0" /&gt;
    &lt;authentication mode="Windows"/&gt;
    &lt;authorization&gt;
      &lt;allow roles="DOMAIN\GROUP"/&gt;
      &lt;deny users="*"/&gt;
    &lt;/authorization&gt;
  &lt;/system.web&gt;
  
  &lt;location path="AccessDenied.aspx"&gt;
  &lt;system.web&gt;
  &lt;authorization&gt;
    &lt;allow users="*"/&gt;
  &lt;/authorization&gt;
  &lt;/system.web&gt;
  &lt;/location&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>I have added this to the Global.asax.cs:</p>
  
  <pre><code>protected void Application_EndRequest(Object sender, EventArgs e)
      {
          if (HttpContext.Current.Response.Status.StartsWith("401"))
              {
                  HttpContext.Current.Response.ClearContent();
                  Server.Execute("AccessDenied.aspx");
              }
  }
  </code></pre>
  
  <p>Any ideas ?</p>
  
  <p><strong>EDIT:</strong>
  I tried some of the posted solutions, but they did not work.
  <strong>But I got it working with this code:</strong></p>
  
  <pre><code>void Application_EndRequest(object sender, System.EventArgs e)
      {
          if (((Response.StatusCode == 401)
          &amp;&amp; (Request.IsAuthenticated == true)))
          {
              Response.ClearContent();
              Response.Redirect("~/AccessDenied.aspx");
          }
      }
  }
  </code></pre>