2
votes

According to How to use custom Errors page in Windows Authentication (although never marked as an answer), you have to add an IIS HTTP error handler to "catch" failed windows authentications and serve up a custom error page.

However, 403 is never reached, failed WinAuth ends with 401 Unauthorized. However, if I add an IIS HTTP error handler for 401, the NTLM authentication process does not work anymore (uses 401 internally as well).

Anybody has a working solution for a custom error page (not static, I want to execute an MVC controller action!) when windows authentication failed?

1

1 Answers

0
votes

The code below isn't exactly what you need, but this is how I am handling unhandled Exceptions. You could alter this to route differently based on status code or exception type. (This is from Global.asax)

 protected void Application_Error(object sender, EventArgs e)
            {
                var ex = Server.GetLastError().GetBaseException();
                Server.ClearError();

                var routeData = new RouteData();
                routeData.Values.Add("controller", "Error");
                routeData.Values.Add("action", "Global");
                int status = 0;

                if (ex.GetType() == typeof(HttpException))
                {
                    var httpException = (HttpException)ex;
                    var code = httpException.GetHttpCode();
                    status = code;
                }
                else
                {
                    status = 500;
                }

                //Create a new error based off the exception and the error status.
                NameSpace.Models.ErrorModel Error = new ErrorModel(status, ex);
                string innerException = "";
                if (ex.InnerException != null)
                {
                    innerException = "\n Inner Ex: " + ex.InnerException.StackTrace;
                }

                log.Error("Error Id: " + Error.ErrorId + " Error: " + ex.Message + ". Stack Trace: " + ex.StackTrace + innerException);
                routeData.Values.Add("error", Error);

                IController errorController = new NameSpace.Controllers.ErrorController();
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));


            }

Update: Apologies, I did not read your post completely. If you were to perform LDAP authentication within your application you could leverage the above code to catch and handle the error with a controller. Unfortunately, I cannot provide direct guidance on your issue above.