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?
Below is my web.config. The lowest part of the code, is something i tried but did not work.
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows"/>
<authorization>
<allow roles="DOMAIN\GROUP"/>
<deny users="*"/>
</authorization>
</system.web>
<location path="AccessDenied.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>
I have added this to the Global.asax.cs:
protected void Application_EndRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Response.Status.StartsWith("401"))
{
HttpContext.Current.Response.ClearContent();
Server.Execute("AccessDenied.aspx");
}
}
Any ideas ?
EDIT: I tried some of the posted solutions, but they did not work. But I got it working with this code:
void Application_EndRequest(object sender, System.EventArgs e)
{
if (((Response.StatusCode == 401)
&& (Request.IsAuthenticated == true)))
{
Response.ClearContent();
Response.Redirect("~/AccessDenied.aspx");
}
}
}
You can use Response.Redirect
or Server.Transfer
Response.Redirect("AccessDenied.aspx");
Full example:
protected void Application_EndRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Response.Status.StartsWith("401"))
{
HttpContext.Current.Response.ClearContent();
Response.Redirect("AccessDenied.aspx");
}
}
Assuming you want to handle all "Unauthorized" errors:
<customErrors defaultRedirect="Error.aspx" mode="On">
<error statusCode="401" redirect="Unauthorized.aspx" />
<error statusCode="403" redirect="Forbidden.aspx" />
</customErrors>
Any 401 (unauthorized) requests will be forwarded to Unauthorized.aspx.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With