Handling PrincipalPermission exceptions in MVC3

865 Views Asked by At

On my MVC application I decorated some of the methods of my controller with this:

[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public ActionResult Create(FormCollection collection)
{
    try {
             ...
    }
    catch {
        return View();
    }
}

And indeed if I am not logged in or not with the correct role an exception is thrown by the MVC application. The problem is I am not getting the application redirected to an error page.

I tried creating a base controller like this:

[HandleError]
public class BaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        // Make use of the exception later
        this.Session["ErrorException"] = filterContext.Exception;

        // Mark exception as handled
        filterContext.ExceptionHandled = true;

        // ... logging, etc

        // Redirect
        filterContext.Result = this.RedirectToAction("Error", "Home");

        base.OnException(filterContext);
    }

}

And then adding the Error view in the Home controller as well as the actual View. The problem is that when I try this in Visual Studio I first get an exception upon entering the protected action method:

 SecurityException was unhandled by the application

and then I have to do Debug|Continue and only then I am redirected to the the Error view but that is unacceptable in a production application because it should go straight to the Error view.

1

There are 1 best solutions below

0
On

Just wondering why you are not just using standard AuthorizeAttribute. Pretty sure it would do that same thing and just work?

E.g.

[Authorize(Roles="Administrator")]
public ActionResult Create(FormCollection collection)

Article on general MVC security here. http://www.codeproject.com/Articles/288631/Secure-ASP-NET-MVC3-applications