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)
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" } })
}
You can also just do the following if you would like to return the proper HTTP response:
filterContext.Result = new HttpUnauthorizedResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With