Search code examples
c#asp.net-mvcsecurityattributesmembership-provider

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!


Solution

  • 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