简体   繁体   中英

Can I have more than one custom Authorize attribute on a controller method?

I created a new Authorize attribute like this:

public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
    private string claimType;
    private int[] claimAllowedValues;

    public ClaimsAuthorizeAttribute(string type, int[] allowedValues)
    {
        this.claimType = type;
        this.claimAllowedValues = allowedValues;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {

        ClaimsIdentity claimsIdentity;
        var httpContext = HttpContext.Current;
        if (!(httpContext.User.Identity is ClaimsIdentity))
        {
            return false;
        }

        claimsIdentity = httpContext.User.Identity as ClaimsIdentity;
        var identityClaimValue = claimsIdentity.FindFirst(claimType).Value;

        if (identityClaimValue != null && 
            claimAllowedValues.Any(n => (n == Int32.Parse(identityClaimValue))))
        {
            return base.IsAuthorized(actionContext);
        }
        return false;
    }
}

It is used here:

[ClaimsAuthorize("Role", new[] { 1, 2, 3 })]

I would like to create another authorize attribute.

Is it possible to create another and then have two of them decorate a method like this:

 [ClaimsAuthorize("Role", new[] { 1, 2, 3 })]
 [OtherAuthorize("abc", 1)]
 [RoutePrefix("api/Question")]
 public class QuestionController : BaseController

我认为这没有道理,您可以通过在自定义的authorize属性中添加更多类型的属性(例如授权类型)来实现同一件事,并在根据需要的场景装饰类时设置这些属性。

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