VJOY
VJOY

Reputation: 3792

How to implement custom role based authorization in ASP.Net MVC

I am working on a project where we are using Amazon SimpleDB as a data storage. In this application user can create roles at run time. While creating role, user can give Read/Write/Update permission for specific feature.

The code I have tried;

using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class MyAuthorization : ActionFilterAttribute
    {
        public string Model { get; set; }
        public string Action { get; set; }

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            //My code will go here
            base.OnActionExecuting(filterContext);
        }
    }

In Web API controller I have written as;

// GET api/values
        [MyAuthorization(Action = "Edit", Model = "Rack")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

Now in OnActionExecuting, I want to fetch Action and Model attributes which I have specified over action method in APIController.

How to handle it through code, since role names and rights are not known at design time.

Upvotes: 1

Views: 3965

Answers (1)

Sankaran
Sankaran

Reputation: 48

I assume that each feature you will be implementing in a certain controller and each action method designates the type of operation you are performing (ex Read, Write etc).

If my assumption is correct, you may have to first extend the AuthorzeAttribute ASP.NET MVC framework like below.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class  CustomAuthorizeAttribute : AuthorizeAttribute
{
   public string Operation;

   public override void OnAuthorization(AuthorizationContext filterContext)
   {
      base.OnAuthorization(filterContext);

      //Get the User Id from the session
      // Get Role associated with the user (probably from database)
      // get the permission associated with the role (like Read, write etc)
      // Let assume the retrieved operations are in the form of list of strings
      List<string> retrievedOperations =RetrieveRoleOperations(userId)         

      if (!retrievedOperations.Contains(Operation)
      {
         filterContext.Result = new HttpUnauthorizedResult();
      }
   }

}

After creating this class, you have to specify the extended authorize filter in required action methods like below.

Class MyFeatureController:Controller
{
     [MyCustomAuthorize(Operation="Read")]
     public ActionResult MyReadMethod()
     {
        //
     }
}

I hope this will solve your problem.

Upvotes: 3

Related Questions