openid:创建基于声明的授权属性 [英] openid: create claim based authorization attribute

查看:125
本文介绍了openid:创建基于声明的授权属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对我的api(web-api 2)实现了SSO,它可以正确验证令牌.但是现在我必须添加一个基于声明的授权属性.在访问令牌中,我有:

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"

我想实现以下目标:

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

因此,如果令牌不包含此声明,我将给出一个401错误.

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?

推荐答案

所以我创建了一个授权属性:

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));
        }
    }

这里适用于控制器:

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

这篇关于openid:创建基于声明的授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆