Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a user will have access to a given Controller Action based on Role

I am trying to build a dynamic menu for my ASP.NET MVC4 web application. As I am constructing the menu I want to make sure that menu items for which a user should not have access are not displayed in the menu.

I am using forms authentication and the [Authorize] attribute with each page requiring a given a role.

Given two strings (Controller and Action), and a logged in user, how can I determine if a user will have access to that Controller Action?


All of my menu data is stored in a database. My plan to render the menu is to construct a JSON object of the menu data and embed that into the View. Then client side I will use Handlebars.js and plug the menu JSON object into a template.


What I am trying to do is check permissions on a given Controller/Action for a user as I am rendering the menu data. My initial thought was to use reflection and look up the controller action method and check for the existence of an Authorize attribute and check to see if the current logged in user has the necessary role access that page. If not, then the menu item would not be rendered.

I am always reluctant to use reflection however, there usually tends to be an easier way of doing things.

like image 234
jdavis Avatar asked Jan 17 '13 15:01

jdavis


People also ask

What is role based Authorisation?

Role-based authorization enables customer management of users and their roles independently from Payment Feature Services. Role-based authorization has a user registry that is not part of Payment Feature Services. This authorization is optional and does not replace the current model.

How do I set roles in AuthorizeAttribute?

And then you can use the Authorize Attribute like so on the Controller Class or the Controller Method (or both): [Authorize(Roles = Roles. ADMIN] public class ExampleController : Controller { [Authorize(Roles = Roles. ADMIN_OR_VIEWER) public ActionResult Create() { ..


1 Answers

public static IEnumerable<MethodInfo> GetActions(string controller, string action)
{
    return Assembly.GetExecutingAssembly().GetTypes()
           .Where(t =>(t.Name == controller && typeof(Controller).IsAssignableFrom(t)))
           .SelectMany(
                type =>
                type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                    .Where(a => a.Name == action && a.ReturnType == typeof(ActionResult))
             );

}

then

var roles = ((AuthorizeAttribute) (GetActions("ControllerName" + "Controller", "ActionName").First().GetCustomAttributes(typeof (AuthorizeAttribute), false)[0])).Roles;
if(roles.Contains("admin or smth"))
{
        doSomsing();
}
like image 108
user355308 Avatar answered Sep 28 '22 09:09

user355308