Friday, April 29, 2005

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"/>
</customErrors>

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">
    <system.web>
        <authorization>
            <allow users="james" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>

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)
    {
        Response.ClearContent();
        Response.Redirect("AccessDenied.htm");
    }
}


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

Nasty!

Thanks to Ashraf Moollan

0 Comments:

Post a Comment

<< Home