Reputation: 820
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();
}
}
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?
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?
Upvotes: 1
Views: 1578
Reputation: 1807
It is possible to specify the resource that specified configuration settings must apply to, using the <location>
element in your configuration file.
More on MSDN here: <location> Element
Update:
For example, you could refine and add something like this.
<location path="Errors/MyCustomPage">
<system.web>
<authorization>
<allow verbs="GET" users="*" />
</authorization>
</system.web>
</location>
Upvotes: 2
Reputation: 1811
Update Enable anonymous authentication for the application through the command line appcmd set config /section:anonymousAuthentication /enabled:true
Upvotes: 1