views:

299

answers:

1

I successfully implemented role based authorization in ASP.NET. When a person does not have the needed role he gets to see an error page for 401.2 not authorized.

What I would like to accomplish now is to have a custom 401 page in my application and have it redirected there via settings in the web.config. I tried this:

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
    <error statusCode="401" redirect="NoAccess.htm" />
</customErrors>

But this does not get caught. Do I have to override it in IIS instead? I hope not as that would make getting things deployed harder.

+2  A: 

I ran into the same problem recently and it turns out that this is one of the quirks when using Windows Authentication.

Joshua Flanagan created a nice HttpModule a while ago that will respect the customErrors section in your web.config and redirect to the 401 error page.

The key to the solution is to intercept the EndRequest event of the page lifecycle, check for a 401 status code, and then execute your custom page.

The portability of the HttpModule is nice because it makes the solution reusable, and keeps your Global.asax clean, but there's nothing stopping you from wiring up your EndRequest event in the Global.asax with his code if you really wanted to.

If you're using ASP.NET MVC, the solution isn't quite as elegant.

Ryan Rivest