AVMP
AVMP

Reputation: 51

Securing Web api Role Based

I hope you're fine, this is my first question and I really don't know where to start from, so here it is,

I've been trying to build a sample with Microsoft Web api Template where I have to authorize users based on roles for example "Admin, Moderators, etc..." so, the thing is the I don't want to put all those roles on the top of the controller like

[Authorize ( Roles ="Admin, Moderators, etc...")]

I see this as not a good practice because What happens if I create another role in my db? I will have to modify the controller to add the new Role xD, really bad, isn't it? so the question is. How to extend some class like AuthorizeFilter to get the roles from database and validate with the controller? I mean if there is a user who is in the role admin authorize it and viceversa?

the other question is How to build a great authorzationfilter which can manage something like if a user if in Moderator Role but the only right he has is to user the Create action in the controller?

I hope you can help me with an example... Thanks in advance

Ps. Sorry for my english

Upvotes: 0

Views: 771

Answers (1)

Jesús López
Jesús López

Reputation: 9221

I agree role based authorization is somehow limited and authorize attribute is a bit rigid.

In some scenarios role based authorization is not enough, you need to extend it. You can introduce the permission concept. Instead of be a requirement that you have to be a member of a specific role to execute an action, you could state that to be authorized to execute an action you need a specific permission. So instead of authorize attribute you use RequiredPermisionAttribute. Of course you need to write RequiredPermissionAttribute as an authorization filter.

In the database you have the Permissions Table, the RolesTable, the RolePermissions table and UsersInRole table.

So a user can be a member of one or more roles. A role can have one or more permissions. A user has a specific permission if he/she is a memeber of a role that has that permission.

The required permission filter checks if the logged in user is a member of a role that has the permission, if not, then returns 401 not authorized.

This is a more flexible approach, actions are not tied to roles and roles don't have a fixed number of permissions.

Upvotes: 1

Related Questions