user1394622
user1394622

Reputation: 67

Entity based security in asp.net MVC4

I have been finding some solution to put security on basis of entity.Like a user can only access to entity to which it has access.

Rather than putting check on each and every action method can i control in centralized way. I am here talking about access entity using ajax call also. For example a user has opened a orderId 10 for that i have an hidden field if by any means if he changes the value of orderId to 11 he can access or modify order with orderId 11 while he was allowed to see only orderId 10 .

There are the time we just send some values along with main entity id for example getOrderByUserId(int userId) as this action method is in OrderController accessing order based on userId.

Upvotes: 1

Views: 225

Answers (2)

serene
serene

Reputation: 685

you are not talking about entity based security but row-wise security as provided by mssql. Entity Based security is if a user is allowed to edit, he will be able to edit any other id.

For this you have to maintain hierarchy of user roles and then storing the minimum role that can perform edit or any action on each row in the table.

Or if you want to block user from using query parameter, you can use parameter or session or TempData to transfer data between actions to transfer id and work.

Upvotes: 0

Nikola Sivkov
Nikola Sivkov

Reputation: 2852

Please take look at AuthorizeAttribute and the roles in specific

usage :

[Authorize(Roles = "manager,admin")]
public ActionResult myMethod(){

 // your code
}

And you can use the Users property and do something like this:

[Authorize(Users = UsersHelper.GetAllowedUsers)]
public ActionResult myMethod(){

 // your code
}

where UsersHelper.GetAllowedUsers is a static class with a static method that returns users in format like this : "joe1,admin,momandpop"

update to OP comment :

/// <summary>
/// Checks if the current user is the owner of the Order
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class IsOwnerOfOrderAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!(filterContext.Result is HttpUnauthorizedResult))
        {
           // code to check if user has the order he is trying to edit
           // if not return this
           filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

you can place this on top of a controller or a specific action.

Upvotes: 2

Related Questions