I have an ASP.NET web-site with authentication using ActiveDirectory.
Now, when an authenticated user opens a page - he is automatically authenticated. I have faced a problem - when a non-authenticated user (for example, a Mozilla Firefox user with not defined network.automatic-ntlm-auth.trusted-uris
property) opens a page, IIS sends 401 response and prompts for a login \ password.
What I want is not to prompt him for a login \ password - just show a custom error page. It sounds pretty simple - authenticated users get the requested page, non-authenticated are redirected to a custom error page. It would work fine for FormsAuthentication.
However, I have tried so many ways by now. Any Web.config redirects are not working. Even if I clear a Response
and put there a redirect - I will get a loop because this custom page (*e.g., /Error/AccessDenied
) also requires authentication. Marking a controller as AllowAnonymous
does nothing.
However, if I enable Anonymous authentication in IIS Manager, real authenticated domain users are not being authorized when they open a web-site.
How can I solve this problem?
Thanks to @Abhitalks for explaining how it works in comments. I don't know why, but I was sure that IE and Google Chrome are sending authorization header on the first request and, that's why, only unauthorized users get 401 response. After I have understood that I cannot avoid 401 response at all, I have decided to use this simple approach as this behaviour is the closest to desirable.
I have added the following method in Global.asax
:
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Response.StatusCode == 401)
{
Response.ClearContent();
Response.WriteFile("~/Static/NotAuthorized.html");
Response.ContentType = "text/html";
}
}
Now, when a user opens a page, the server returns him a custom error page but with 401 Unauthorized
header.
Chrome, IE or well-configured Firefox. Users requests an URL, the server returns the error page with 401 header - a browser automatically completes authorization challenge, redirects to the same URL, the server returns the correct page and 200 now. The user will not see this error page.
Non-configured Firefox. User requests an URL, the server returns the error page with 401 header - a browser cannot complete authorization challenge and prompts user for credentials.
User enters correct login. User requests the same URL again, gets a page and 200 OK.
User enters incorrect login. A browser prompts for credentials again.
User presses Cancel. A browser displays the custom error page which has been sent with header 401. This page tells the user that if he is using Firefox, then he should either enter his credentials or allow automatic NTLM authentication.