简体   繁体   中英

How to allow [Authorize] inside a custom AuthorizeAttribute

I have a custom AuthorizeAttribute like this

public class DevMode : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (myConditionToAuthorize)
        {
            // how to allow [Authorize] ?
        }
    }
}

The problem is that it is used along with [Authorize] tag like this:

[Authorize, DevMode]
public class UserController : ApiController { ... }

I need to allow [Authorize] == true inside [DevMode]

Or it is better to put them all together inside a unique authorize class? But then I dont know tho to check Authorize data.

Or it is better to put them all together inside a unique authorize class?

Oh yes, that would indeed be better. You could simply derive from the AuthorizeAttribute and call the base method:

public class DevModeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var authorize = base.IsAuthorized(actionContext);
        if (!authorized)
        {
            // the user is not authorized, no need to go any further
            return false;
        }

        // now apply your custom authorization logic here and return true or false
        ...
    }
}

and then:

[DevMode]
public class UserController : ApiController { ... }

I used this to add a custom IsAdmin (based on claims) using this method

public class IsAdminAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        IPrincipal principal = actionContext.RequestContext.Principal;
        return principal.IsAdmin();
    }
}

it kind of answers my own last comment so hope it helps someone else please note the .IsAdmin is an extension method on the IPrincipal that checks claims.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM