Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display a custom error page for an Http 401 result?

Tags:

asp.net-mvc

I have a controller with an Authorize attribute like this:

[Authorize(Roles = "Viewer")]
public class HomeController : Controller
{
   //...
}

and my web.config has customErrors set like the following:

<customErrors mode="On">
      <error statusCode="401" redirect="notauthorized.html"/>
  </customErrors>

When I try to invoke an action on the Home controller using a non-authorized role I just get a blank page. I don't get redirected to the custom page. Any ideas?

like image 967
Marco M. Avatar asked Sep 14 '09 15:09

Marco M.


2 Answers

I appreciate this question is a little old, but this may help someone.

For a 401 you will probably be seeing the standard 401 Unauthorised page, even if you have added 401 to the customerrors section in your web.config. I read that when using IIS and Windows Authentication the check happens before ASP.NET even sees the request, hence you see the blank page on Cassini and on IIS it's own 401.

For my project I edited the Global.asax file to redirect to a route I had created for 401 errors, sending the user to the "Unauthorised to see this" view.

In the Global.asax:

    void Application_EndRequest(object sender, System.EventArgs e)
    {
        // If the user is not authorised to see this page or access this function, send them to the error page.
        if (Response.StatusCode == 401)
        {
            Response.ClearContent();
            Response.RedirectToRoute("ErrorHandler", (RouteTable.Routes["ErrorHandler"] as Route).Defaults);
        }
    }

and in the Route.config:

        routes.MapRoute(
        "ErrorHandler",
        "Error/{action}/{errMsg}",
        new { controller = "Error", action = "Unauthorised", errMsg = UrlParameter.Optional }
        );

and in the controller:

    public ViewResult Unauthorised()
    {
        //Response.StatusCode = 401; // Do not set this or else you get a redirect loop
        return View();
    }
like image 57
VictorySaber Avatar answered Nov 01 '22 12:11

VictorySaber


Take a look at tvanfosson's Answer from this very similar question, This is what I am doing(Thanks to tvanfosson), so now I just have to say:

[MyAuthorize(Roles="SuperAdmin",ViewName="AccessDenied")]
public class SuperAdminController : Controller
...

If the user is not in the role, they will get thew view specified by ViewName.

Note: the blank page is coming from Cassini, if you move the app to an actual IIS server you will see the 401.

like image 41
KP. Avatar answered Nov 01 '22 13:11

KP.