问题
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