Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom AuthorizeAttributte with Enum Roles params getting null Values in ajax call

I'm having some problem with my custom AuthorizeAttribute

public class ExplicitAuthorizeAttribute : AuthorizeAttribute
{
    private readonly MembershipUserRole[] _acceptedRoles;

    public ExplicitAuthorizeAttribute()
    {

    }

    public ExplicitAuthorizeAttribute(params MembershipUserRole[] acceptedRoles)
    {
        _acceptedRoles = acceptedRoles;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {  
       //Validation ...          
    }
}

I use it like this:

[ExplicitAuthorize[(MembershipUserRole.Admin, MembershipUserRole.SuperAdmin)]

It works perfectly for HttpGet and HttpPost to validate my controllers and methods.

But when I use it in a ApiController and make ajax calls, AuthorizeCore isn't running and I got a security breach. :/

My enum looks like this

[Flags]
public enum MembershipUserRole
{
    Admin= 1,
    SuperAdmin = 2
}

Does anyone know why my AuthorizeCore isn't validating in this context?

By the way If I use

[Authorized(Roles ="Admin, SuperAdmin")]

It's validates perfectly, but I'd like to have Stronly Typed Roles,that's why I'm using enums.

like image 440
nramirez Avatar asked Oct 25 '13 17:10

nramirez


1 Answers

You have derived from the wrong class: System.Web.Mvc.AuthorizeAttribute whereas for a Web API controller you should derive from System.Web.Http.AuthorizeAttribute.

Don't forget that ASP.NET MVC and ASP.NET Web API are 2 completely different frameworks and even if they share some common principles and names, the corresponding classes are located in 2 completely different namespaces.

So what you have done is decorate an ASP.NET Web API action with an AuthorizeAttribute that it doesn't know anything about.

If you want to make authorization in ASP.NET Web API make sure you have derived from the correct attribute:

public class ExplicitAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    private readonly MembershipUserRole[] _acceptedRoles;

    public ExplicitAuthorizeAttribute()
    {

    }

    public ExplicitAuthorizeAttribute(params MembershipUserRole[] acceptedRoles)
    {
        _acceptedRoles = acceptedRoles;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        //Validation ...          
    }
}
like image 151
Darin Dimitrov Avatar answered Sep 30 '22 13:09

Darin Dimitrov