Custom 401 error pages in MVC alongside Windows Authentication

Custom 401 error pages in MVC alongside Windows Authentication

We use windows authentication for a lot of our web apps, but also want to serve up a custom 401 error page when users are not authorized to log in. This is tricky because this specific 401 error is handled directly by IIS, rather than the application itself, because it’s a windows directory permission. I spent quite a bit of time searching for an elegant solution to this, but really came up with nothing. This is one way I’ve found to circumvent the issue, and serve up a custom 401, while still preserving your MVC application level error handling:

1) You will need an entry for your 401 error page in the httpErrors section of web.config:


<httpErrors errorMode="Custom">

	<remove statusCode="401" />

	<error statusCode="401" path="Views\Error\401.html" responseMode="File" />

</httpErrors>

2) You will then need to go into IIS and enable anonymous authentication AND windows authentication for your content folder, or whatever folder houses all your images and css used on your error page and throughout the rest of your application. I could not find a way to successfully enable this through the application’s web.config solely.

iis auth

This will now allow you to show a custom 401 error page, with images and css, to an unauthorized user. Once the user is authenticated successfully, they will still see the expected images and css.

If there is a better way to achieve this functionality, that I’m missing, please leave a comment and let me know, thanks!

By | 2018-03-05T22:32:04+00:00 February 3rd, 2015|Categories: ASP.NET, IIS, MVC|Tags: , , |2 Comments

About the Author:

2 Comments

  1. Greg K May 16, 2017 at 8:38 am - Reply

    Is there a way to redirect using the Error.cshtml instead of a static file?

    • Brent May 16, 2017 at 8:41 am - Reply

      Hi Greg,

      Off the top of my head, I am not sure. I would have to dig into that more myself, sorry.

Leave A Comment