Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically mapping roles to controllers in ASP.Net MVC

I am currently hard coding the authorized roles in the filter in my MVC applications like so:

[Authorize(Roles = "Administrator,Manager")]

I'd like to eventually have a way to map the roles to each controller, so that the site admin can handle assigning what roles can perform each set of actions.

string roles = DoSomethingToGetAllowableRoles(controllerName);

[Authorize(Roles = roles)]

I'm imagining that I need to have a database table that somehow keeps a listing of each controller, and then another table mapping the controllers to the roles. What I'd like is a page where I can list out each controller and then have a set of check boxes that lists each role that applies to that controller.

Anyone have an example or can lead me in a direction that will accomplish this?

like image 841
Ben Avatar asked Sep 22 '10 02:09

Ben


People also ask

What are the roles of a controller in ASP.NET MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

Can we have two Controllers with same name in MVC?

One should be of type Controller, and the other ApiController, then they can both exist with the same name.

Can we pass data from view to controller in MVC?

You can do it with ViewModels like how you passed data from your controller to view. and in your HttpPost action, use a parameter with same name as the textbox name. If you want to post to another controller, you may use this overload of the BeginForm method.


1 Answers

You're going to need to write your own authorization filter (probably by extending the built in one).

The reason for this is that you can't assign attribute parameters dynamically like that.

You won't need to mess with the MVC source code - you just need to create a class which inherits from System.Web.Mvc.AuthrorizeAttribute, override AuthorizeCore, and then use your attribute in place of the default:

public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Put your custom logic here, returning true for success and false for failure,
        // or return base.AuthorizeCore(httpContext) to defer to the base implementation
    }
}
like image 169
Bennor McCarthy Avatar answered Nov 15 '22 05:11

Bennor McCarthy