openid: create claim based authorization attribute

为君一笑 提交于 2019-12-12 06:38:19

问题


I have implemented SSO to my api (web-api 2) and it's validating correctly the token. But now I have to add a claim based authorization attribute. In the access token I have:

 "MyClaim.Read.All": "true"

And I would like to achieve something like:

[ClaimAuthorizationAttribute("MyClaim.Read.All")]
public sealed class MerchantProfileController : ApiController

So that if the token doesn't contain this claim, I would give a 401 error.

How to achieve this, so I can use this attribute to any controller I want with any claim?


回答1:


So I've created an authorization attribute:

    [AttributeUsage(AttributeTargets.All)]
    public sealed class ClaimAuthorizationAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// Gets or sets the claim to check in the web token
        /// </summary>
        public string Claim { get; set; }

        /// <inheritdoc/>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            var decoder = new JwtSecurityTokenHandler();

            var token = (JwtSecurityToken)decoder.ReadToken(actionContext.Request.Headers.Authorization.Parameter);

            return token.Claims.Any(c => c.Type.Equals(this.Claim) && c.Value.Equals("True", StringComparison.OrdinalIgnoreCase));
        }
    }

And here is applied to a controller:

[ClaimAuthorization(Claim = "MyClaim.Read.All")]


来源:https://stackoverflow.com/questions/42007131/openid-create-claim-based-authorization-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!