Asp.net MVC - How can I get user roles without knowing these roles?

I am working on this project so that an admin user can create multiple user groups that will act as project roles.

So, the administrator will create a user group named "SuperAdmin" and select from the drop-down list the users who will be part of this group.

I've worked before in a solution using RoleProvider and using Controller Attibutes, but in this case I created all the groups and manually set in the controller, e.g .:

[Access(Roles = "SuperAdmin")]
public UserController : Controller
{
}

      

In the example above, I know the group is called SuperAdmin. But now, in this new project, I don't know what groups the admin user will create.

So how can I get all the roles that a user will be allowed access dynamically?

Thank!

+2


source to share


2 answers


If I understand your question correctly, you want to soft-code the "SuperAdmin" value.

I ran into a similar problem as I wanted to make sure that the user had access to a specific resource (call it as a document), but that resource ID was unknown during application development. I solved this by creating my own table based security and putting the main logic of my model (actually the business logic layer) in it. This allows me to fetch data protection data from the database and redirect the user if they request a resource for which they do not have access.

If you still want to do this with an attribute, you can create a custom attribute (simulating the one that ASP.NET MVC uses) that looks for the appropriate permissions from the database and makes the definition.

Or, you can do it right inside a 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 details here: Document Based Security in ASP.NET MVC

+4


source


Have you considered your own attribute that you can decorate with your action?

In this case, you can use this attribute to get the access rights for the user, map that to the page access table, and then return the result and allow or deny access to the page / action.

I think you will need to have a table that will determine which pages the role has access to, to which a link to the roles that the user is assigned can be attached to.



Or, you can write your attribute to define the roles that are allowed to view the page.

[MyAccessAttribute(Allow="SuperUser", "Admin")]
public ActionResult MyAction()

      

Does it help / make sense?

+1


source







All Articles