Custom AuthorizeAttributte with Enum Roles parameters getting null Values ​​in ajax call

I am having a problem with my custom attribute 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 as follows:

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

It works great for HttpGet and HttpPost to test my controllers and methods.

But when I use it in ApiController and make ajax calls, AuthorizeCore does not work, and I received a security violation.: /

My listing is as follows

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

Does anyone know why my AuthorizeCore does not check in this context?

By the way, if I use

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

It is well-tested, but I would like to have strong typed roles, so I use enums.

+6
source share
1 answer

You got from the wrong class: System.Web.Mvc.AuthorizeAttribute , whereas for the web API controller you should get System.Web.Http.AuthorizeAttribute .

Do not forget that ASP.NET MVC and ASP.NET Web API are two completely different structures, and even if they have common principles and names, the corresponding classes are located in 2 completely different namespaces.

So what you did was decorate the ASP.NET web API action with the AuthorizeAttribute attribute, which he knows nothing about.

If you want to make authorization in the ASP.NET Web API, make sure that you get 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 ... } } 
+5
source

Source: https://habr.com/ru/post/956735/


All Articles