I'm not quite sure why I am struggling with this as I'm sure it should be simple. I've created an MVC 5 web application which is based on .net 4.5. I've enable windows authentication in the web.config as below;
<system.web>
<Authentication mode="windows" />
</system.web>
This is working perfectly. I was actually surprised at how easy the new framework makes it. When a user navigates to my site it authenticates them and logs them in which is cool. When it cannot authenticate the user it produces a 401 error, I want to provide a custom page for this error. In order to catch the 401 I used the following pseudo code;
public class GlobalErrorAttribute : ErrorHandlerAttribute
{
public override OnError(filterContext _context)
{
if(statusCode = 401)
{
_context.Result = RedirectTo("~/Errors/MyCustomPage");
}
}
}
This redirect of course requires a controller which is fine, it's very basic;
public class ErrorsController : Controller
{
public ActionResult MyCustomPage()
{
return View();
}
}
My Issue
This wonderful error page which it redirects to, throws a 401 because it is still trying to authenticate. [AllowAnonymoous] will not work as this is authorization. How do I stop MVC attempting to authenticate?
It must be easy, I can think of a common example where you would want this behavior. A public facing website might want to use windows authentication for employees on premise but allow the public to browse un-Authenticated.
How can I achieve this?
Update
When the user is not Authenticated the 401 bypasses my GlobalErrorAttribute?!? How can I turn authentication off for a page? Like it does for the custom error page?