Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permissions for roles in .NET

Tags:

c#

.net

asp.net

I'm using the standard .NET authentication database tables and code, with .NET 4.0, C# and MVC 3.

Basically, I want to have roles (which are included in the framework), and then be able to assign permissions to those roles (which are not included, as far as I know).

So I want to assign permissions to roles. A user in the Accountant role couldn't edit and delete employees, but a user in the Administrator role could. Since these permissions could change at any time, instead of checking User.IsInRole("Administrator"), I'd like to do something like User.HasPermission("EditEmployee").

I could probably design some custom tables and code myself, but I'd rather use the .NET Framework if it's already built-in. Is there anything like this? If not, is there a library out there that does do this?

like image 338
Steven Avatar asked Aug 02 '11 20:08

Steven


2 Answers

The built-in RoleProvider really doesn't offer a clean way of doing this. Really the only way to do it with the RoleProvider is to create roles like "Employees_CanEdit" and "Employees_CanAdd" and so on, but then you end up with a huge mess of roles floating around.

There's other ways of having permissions with your roles, though. You could make a table that links a user, a role("Employees"), and a permission("Add" or "Edit"). Then you could implement something like:

public bool HasPermission(string role, string permission) {
    // Some sql for accessing the table
    // return true if a row exists that matches the user, the role, and the permission
}
like image 180
rossisdead Avatar answered Sep 29 '22 20:09

rossisdead


Maybe you could simply add another role to user who can edits employees. Something like "CanEditEmployee" and then verify if user is in role "CanEditEmployee"? This is what I do when I must have to do something similar.

like image 33
Simon Dugré Avatar answered Sep 29 '22 20:09

Simon Dugré