Vishal Suthar
Vishal Suthar

Reputation: 17194

Role-Based Access Control to a User

I have an application MVC 4.0 using Entity Framework.

I have a USER table, Role table, Type table.

Role can be out of the two: Administrator, User

Type can be out of 8: None, Admin, Asst.Admin, ......

So I want to allow different pages to be accessed based on the type as below:

1) Types defined:

None    Con     Acc     Rec     St      Fr      Admin  AsAd  ( <-- Types)
----------------------------------------------------------

1.a) Update client:

None    None    None    None    Edit    View    Full  Full  ( <-- Roles)

1.b) New Client:

None    None    None    View    View    Edit    Full  Full  ( <-- Roles)

So how will this be achieved ?

Upvotes: 1

Views: 801

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

You can achieve this with an AuthorizeAttribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ActionPermissionAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var actionName = filterContext.ActionDescriptor.ActionName;

Add this attribute to all the Actions you need to have authorised - add at the controller makes this easier or even create a base controller that inherits Controller and then inherit all your controllers from that.

You can then store your controller+action vs role in the DB

        // get allowed groups for this controller+action from the database (cache this)
        // get which AD groups the current user is in (or get from the DB etc)
        var userGroups = HttpContext.Current.Request.LogonUserIdentity.Groups
                         .Translate(typeof(System.Security.Principal.NTAccount))
        // check if user in in required group 

If you really want to have permissions defined in code per action, then just add properties to the attribute and attribute constructor as required.

I didn't fully understand your role vs type, but in MVC everything is an action (method) so you lock down individual actions (there's no 'edit' just an action called 'edit').

Upvotes: 1

Related Questions