Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 Authorize Attribute overide; how to get passed in Roles?

I'm trying to create my own [Authorize] Attribute so I can use my own authorize logic to have hierarchal roles.

If someone does [Authorize(Roles = "Admin")] on a controller or action How do I get the string "Admin" in my AuthorizeCore function?

I'm using this code:

public class Authorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //authorize role logic
            if (true)
                return true;

        return false;
     }
    }

MVC4, .net 4.5, c#, VS 2012

like image 913
Kyle Avatar asked Dec 13 '12 21:12

Kyle


People also ask

How do I override an authorized attribute in .NET core?

We have code base ready, we need to implement the wrapper class to handle the API request. Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method.

How does the Authorize attribute work?

The Authorize Attribute This means that once the request matches a supported route and is resolved to controller and method, it gets executed no matter what. Put another way, any public method defined on the controller class can be run if only the user calls the right URL.


2 Answers

It is quit a common thing that you have faced with.

This recommendation in post should work in MVC4 as it is working in MVC 3: - ASP.NET MVC - Alternative to Role Provider?

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool isAdmin;
        if(Roles.Contains("Admin"))
           isAdmin = true;

        return isAdmin ;
    }
like image 55
Yusubov Avatar answered Sep 18 '22 02:09

Yusubov


Roles is a public property. You should be able to do this:

public class Authorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {

        if(Roles.Contains("MyRole"))
           return true;

        return false;
    }
}

Or whatever it is that you need to do

like image 29
devlife Avatar answered Sep 22 '22 02:09

devlife