Asp.net MVC - How can I get user roles without knowing these roles?
I'm working on this project that an admin user can create some User's Groups that will be working as the project roles.
So, the admin will create a User Group named "SuperAdmin" and will select in a dropdownlist the users that will be part of this group.
I've worked before in a solution using RoleProvider and using Controller's Attibutes, but in that occasion I created all the groups and set manually in the Controller, like:
[Access(Roles = "SuperAdmin")]
public UserController : Controller
{
}
In the example above I know that 开发者_开发技巧the group is named "SuperAdmin". But, now, in this new project, I don't know what groups an admin user will create.
So how can I get all roles that a user will be allowed to access dynamically?
Thanks!
If I understand your question correctly, you want to soft-code the value "SuperAdmin".
I encountered a similar problem, as I wanted to verify that a user had access to a certain resource (call it a document), but that resource's ID was unknown during application development. I solved it by creating my own table-based security and putting the core logic for it in my model (effectively the business logic layer). This allows me to security-trim data retrievals from the database, and redirect a user if they are requesting a resource for which they have no access.
If you still want to do it with an attribute, you can create a custom attribute (modeling the one that ASP.NET MVC uses) that looks up the appropriate permissions from the database, and makes a determination.
Or, you can do it right inside the controller method, using something like this:
Public ActionResult EditThing(int ID)
{
ThingRepository repository = new ThingRepository();
If (!repository.UserHasAccess(int ID))
Return View("NotAuthorized")
//
// Do stuff here
}
See the NerdDinner tutorial if you need more information on repositories.
More info here: Document-Based Security in ASP.NET MVC
Have you considered writing your own attribute that you can decorate your action with?
In that case you could use the attribute to get the access rights for a user, match that against say a page access table and then return the result and either allow or deny access to the page/action.
I think you'll need to have a table which will dictate which pages a role has access to which can be cross referenced to the roles a user is assigned to.
Or you could write your attribute in such a way so that it dictates the roles allowed to see the page.
[MyAccessAttribute(Allow="SuperUser", "Admin")]
public ActionResult MyAction()
Does this help / make sense?
精彩评论