Ryan Roark
Ryan Roark

Reputation: 61

Using ClaimsPrincipalPermissionAttribute, how do I catch the SecurityException?

In my MVC application I have a Controller Action that Deletes a customer, which I'm applying Claims Based Authorization to using WIF.

Problem: if someone doesn't have access they see an exception in the browser (complete with stacktrace), but I'd rather just redirect them.

This works and allows me to redirect:

public ActionResult Delete(int id)
{
    try
    {
        ClaimsPrincipalPermission.CheckAccess("Customer", "Delete");
        _supplier.Delete(id);
        return RedirectToAction("List");
    }
    catch (SecurityException ex)
    {
        return RedirectToAction("NotAuthorized", "Account");
    }
}

This works but throws a SecurityException I don't know how to catch (when the user is not authorized):

[ClaimsPrincipalPermission(SecurityAction.Demand, Operation = "Delete", Resource =     "Customer")]
public ActionResult Delete(int id)
{
    _supplier.Delete(id);
    return RedirectToAction("List");
}

I'd like to use the declarative approach, but not sure how to handle unauthorized requests. Any suggestions?

Upvotes: 1

Views: 1996

Answers (1)

jlnorsworthy
jlnorsworthy

Reputation: 3974

You can use the HandleError attribute. You can check out its usage here: ASP.Net MVC Preview 4 release

Essentially, you should be able to decorate your Delete ActionResult with the HandleError attribute and specify the exception type to catch and the view to show, like this:

[HandleError(ExceptionType = typeof(SecurityException), View = "UnauthorizedView")]

You would, of course, have to create that UnauthorizedView. If you don't specify a view, you'll get a standard Error view (Located in the Shared Views folder)

Upvotes: 1

Related Questions