Martijn
Martijn

Reputation: 45

How can I access the Authorized Roles for a controller?

I have a asp mvc application that has controllers with authorization. Is it possible to access the content of the Roles string?

[Authorize(Roles = "Medialen, Admin, Verkoop, Medewerker")]
public class BaseController : Controller
{

So for the controller above it should return "Medialen, Admin, Verkoop, Medewerker"

Upvotes: 1

Views: 1275

Answers (2)

ivamax9
ivamax9

Reputation: 2629

Brian Mains answer is actually right, but exist another variants how to do this:

You can create custom attribute, which inherit from Authorize attribute and do your things inside OnAuthorization Method.

public class YourAuthorizationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var roles = this.Roles;            
        //your things   
        base.OnAuthorization(filterContext);
    }    
}

And then use it with your actions or controllers

[YourAuthorizationAttribute (Roles = "Medialen, Admin, Verkoop, Medewerker")]

Also exist another silly variant get current roles inside in Action if you have list of all existing Roles in system:

public ActionResult Index()
{
     var roles = GetListOfRoles(); //Get all list of roles, for example from db
     var currentRoles = roles.Where(User.IsInRole);
     ....
}

But if you want some secure check the first one is better.

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

You can use reflection to grab the attribute definition like the following.

public ActionResult SOmeAction()
{
   //this refers to controller, GetCustomAttribute looks for attribute on controller
   //GetCustomAttribute is a 4.5 extension method
   var attrib = this.GetType().GetCustomAttribute<AuthorizeAttribute>();
   if (attrib != null)
   {
      var roles = attrib.Roles;
   }
}

So it looks at the controller level; it can be enhanced to look at the method too. I'm assuming you are trying to get this information from within an action method, but you can always look to grab it from a filter attribute too, depending on how you want to use it.

Upvotes: 2

Related Questions