Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get roles array from Authorize Attribute of certain action in ASP.NET MVC?

Suppose I have following Controller and action with authorization Attribute:

    public class IndexController : Controller
    {
        //
        // GET: /Index/

        [Authorize(Roles="Registered")]
        public ActionResult Index()
        {
            return View();
        }

    }

I've searched over the entire Internet and not found an answer for this simple question: how to get the roles annotated to an especific Action/Controller? In this case: Index Action has: string[] = {"Registered"}

like image 583
Lucas Batistussi Avatar asked Oct 05 '22 17:10

Lucas Batistussi


1 Answers

Finally I found the solution! Was more easy than I thought! ahahha I need extend a class from AuthorizeAttribute and use it in actions. The information I need is the attribute "Roles" of the inherited class:

public class CustomAuthorizationAttribute : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {

        var roles = this.Roles;

        base.OnAuthorization(filterContext);
    }

}

And on Index Controller:

public class IndexController : Controller
    {
        //
        // GET: /Index/

        [CustomAuthorizationAttribute(Roles = "Registered")]
        public ActionResult Index()
        {
            return View();
        }

    }
like image 60
Lucas Batistussi Avatar answered Oct 10 '22 01:10

Lucas Batistussi