Nasty little ASP.NET 401 problem

I discovered this nasty little problem the other day while building a couple of simple little pages and I thought I should post it so I don’t forget and waste ages on it again!

Essentially the issue is that if you have custom error pages for different types of http status codes such as 401, 403 or 404 then you will have be prepared to do a little bit coding for your 401 page to be displayed unlike your other error pages which you can automatically redirect to by turning on customErrors in the web.config file like so:

<customErrors mode=”Off” defaultRedirect=”Error.htm” >
<error statusCode=”403″ redirect=”AccessDenied.htm”/>

The problem with 401 is that if you are using the web.config authorisation section as well, and you have explicitly denied the user permission then their request will be authenticated but not authorised and appears to be terminated before the ASP.NET custom error handler can run. For example:

<location path=”MySecurePage.aspx”>
<allow users=”james” />
<deny users=”*” />

Here the only way to redirect your user to your custom error page will be to check for this condition in the application_end event in the global.asax like so:

protected void Application_EndRequest(Object sender, EventArgs e)
if (Response.StatusCode == 401 && Request.IsAuthenticated == true)

Note: trying to set your custom 401 page in IIS won’t work either as user is authenticated by IIS, but their authorisation fails at the ASP.NET level


Thanks to Ashraf Moollan

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s