Question

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

Was it helpful?

Solution

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 ;
    }

OTHER TIPS

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

If you need to get the list of allowed roles, you can simply get the Roles property. It will list the string that was specified in the attribute decoration.

public class Authorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var allowedRoles = Roles;
    }
}

You can see this on the AuthorizeAttribute definition

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top