bh213
bh213

Reputation: 6519

ASP.NET MVC: How to show a specific view as result of failed authorization in IAuthorizationFilter

I have IAuthorizationFilter filter that checks for specific roles. In case user doesn't have specified roles, I'd like to show a specific view that says something along the lines of "You don't have privileges to view this page".

I'd also like to show this view on specific url, so redirect is not an option.

Here is what I want:

1) User goes to /Admin/Payments 2) /Admin/Payments requires Admin rights 3) User is not an admin. 4) User is show page that says that he cannot access this page, yet url is /Admin/Payments

Thanks.

Upvotes: 1

Views: 624

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        // TODO: do your authorization or if you want to keep the default
        // simlpy invoke the base method
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Shared/Unauthorized.cshtml"
        };
    }
}

and then:

[MyAuthorize(Roles = "Admin")]
public ActionResult Payments()
{
    ...
}

Upvotes: 3

Related Questions