Thursday, May 14, 2015

Custom Error And Stack Trace in MVC

In today's blog post, we will be discussing how harmful can a visible stack trace be and how we can avoid it.

Stack Trace

When the application throws an exception, we see the stack trace in the browser. This information is very valuable to someone who is trying to compromise your web application. The stack trace exposes the internal code structure and framework information. It also shows what caused the exception and it gives insight to the outsider how he can make the application fail.




Custom Error

In order to avoid leaking such information, we must set the customError mode in the config file. Inside system.web section of the web.config, we can set custom errors like this:

    <customErrors mode="On" defaultRedirect="/Error/Error">
      <error statusCode="403" redirect="/Error/UnAuthorized"/>
    </customErrors>


The mode can be set to On, Off or RemoteOnly - depending on the application needs. defaultRedirect is set to the path to which to redirect once an unhandled exception occurs. We can also set specific paths for different status codes. For example, for 403 Forbidden, we might want to show a separate view.

Here is how the ErrorController looks like:

public class ErrorController : Controller

    {

        public ActionResult Error()

        {

            return View();

        }



        public ActionResult UnAuthorized()

        {

            return View();

        }

    }

Now, if a generic exception occurs, the error page looks like this:



And if an unauthorized exception is thrown in the application, the page looks like this:



Conclusion

Proper Configuration for custom error is important for the safety of the web application. Custom Error setting in web config allows us to hide the sensitive information from being misused.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)



No comments:

Post a Comment