7
votes

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?

3
possible duplicate of ASP.NET Security Roles AND PermissionsDan J
@djacobson - Yeah, I saw that post. It was posted over 2 years ago though, so I didn't know if maybe since then .NET 4.0 included this feature, or if a third-party developed this feature as a library.Steven
I created my own framework to do this that looked like the roles api, but instead used rights. Most apps seem to implement their own classes to do this as it adds more flexibility over simple role checking.Simon Halsey

3 Answers

2
votes

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
}
1
votes

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.

1
votes

Normally when I want to do something like this, I create sub-roles using the underscore symbol "_" the segmented the additional permissions/capabilities the sub-role provides.

Example:

Administrator Administrator_EditEmployee Administrator_EnableTasks etc...

I then parse the names in my management pages so I get a nicely formatted nested treeview / drop down list which I then assign to various users. This way, you can continue to use the built-in security system without having to add anything special other than some parsing logic in your management pages.