Steven
Steven

Reputation: 18869

Permissions for roles in .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?

Upvotes: 7

Views: 4241

Answers (3)

rossisdead
rossisdead

Reputation: 2108

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
}

Upvotes: 2

Zachary
Zachary

Reputation: 6532

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.

Upvotes: 1

Simon Dugré
Simon Dugré

Reputation: 18946

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.

Upvotes: 1

Related Questions