ASP.NET MVC authorize attribute using action parameters with the ActionFilterAttribute

ASP.NET MVC provides the AuthorizeAttribute which ensures there is a logged in user. You can also provide parameters to restrict actions or controllers to only be accessible to certain roles or users. You can also create your own custom authorization attribute derived from AuthorizeAttribute to provide any custom authorization.

In addition to this general authorization you may want to restrict access based on the current user and a parameter from the action. For example, say you have an action method to edit the details of a product.  You would pass the ID of the product to the action method, and you may only want certain users to be able to edit this particular product.  The AuthorizeAttribute doesn’t allow you to do this but you can create your own attribute derived from ActionFilterAttribute which gives you the desired result.

When creating your own attribute deriving from ActionFilterAttribute, you can override the OnActionExecuting method. This method has an ActionExecutingContext parameter which contains an ActionParameters collection which allows you to get your ID. It also has a HttpContext property allowing you to get the logged in user.  Using these you can easily perform the type of authorization required.  The example class below shows how this could be done.

public class ProductAuthorizeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        //Get the id from the action parameter
        int id = Convert.ToInt32(filterContext.ActionParameters["id"]);
        //Get the current user
        string username = filterContext.HttpContext.User.Identity.Name;

        bool isAuthorised = false;
        //Perform some check that the user is allowed to access the product with the given id
        //eg. isAuthorised = UserService.UserCanEditProduct(username, id);
        if (!isAuthorised)
        {
            //This will redirect the user to the login page
            //You could use a view displaying an error message
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

If you set the FilterContent.Result property it changes the result of the action method; here I’m setting it to a new HttpUnauthorizedResult which will redirect the user to the login page.

Posted on by Joe in C#, MVC

One Response to ASP.NET MVC authorize attribute using action parameters with the ActionFilterAttribute

  1. Pingback: Tweets that mention ASP.NET MVC authorize attribute using action parameters with the ActionFilterAttribute | Joe Stevens' Blog -- Topsy.com

Add a Comment