Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an AuthorizationAttribute prevent an action from being executed entirely?

I've got a custom AuthorizationAttribute that appeared to be working on the surface. When a user without the correct permissions requests an action via the browser, they are shown the appropriate message.

I started applying this attribute to HttpPost actions that do things like delete. Even though the response is correct, the body of the action still executes (in this instance the item is deleted).

What I want to be able to do is completely prevent the action method from doing anything if the authorization attribute fails. Is this what AuthorizationAttributes are for, or should I looking at another way?

Update:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    Check.Require(filterContext != null);

    if (service.HasPermission(requiredPermission))
        return;

    filterContext.HttpContext.Response.StatusCode = 404;
    filterContext.HttpContext.Response.StatusDescription = "File not found";
}

The controller action is being decorated like this:

[HttpPost, RequiresPermission(Permissions.CanDeleteContentItem)]
public JsonResult Delete(Guid id)
like image 800
Michael Shimmins Avatar asked Jan 02 '11 04:01

Michael Shimmins


1 Answers

Check out my answer here as it's similar to what you're trying to accomplish.

What you need to do is change the result that is returned by the action instead of just changing the header values.

public override void OnAuthorization(AuthorizationContext filterContext)
{
    Check.Require(filterContext != null);

    if (service.HasPermission(requiredPermission))
        return;

    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, {"action", "NoPermission" } })
}

Update

You can also just do the following if you would like to return the proper HTTP response:

filterContext.Result = new HttpUnauthorizedResult();
like image 103
Omar Avatar answered Oct 04 '22 22:10

Omar