检查Claim数组以获取特定值



如果我有

services.AddAuthorization(config =>
{
config.AddPolicy("IsDeveloper", policy => policy.RequireClaim("developer","true"));                                
});

我的JWT令牌包含

"permissions": [        
"customer_get",
"customer_update",
"customer_create",
"customer_delete",
"developer"
]

然后我试图用来保护我的blazor网站

@attribute [Authorize(Policy = "IsDeveloper")]
<AuthorizeView Policy="IsDeveloper">
<p>You can only see this if you're an admin or superuser.</p>
</AuthorizeView>

我在这个实现中做错了什么?不能这样使用requireClaim吗?我必须在这里做一些不同的事情?

当我的JWT令牌只包含:时,它就工作了

"permissions": "developer"

所以我可以。只需将它们添加为,Name=true。。但是尽管阵列更容易读取

这是一篇老文章,但我也花了一段时间试图弄清楚,所以这是我的解决方案。同样的概念,我有一个jwt,里面有几个"声明"、Id、用户名、角色等。

{
"id": "4d2ds1fg-12da-4fg6-f57h-34gdfg33g33f",
"email": "joe@bloggs.com",
"username": "joe@bloggs.com",
"firstname": "Joe",
"surname": "Bloggs",
"role": "admin",
"claims": [
"CanCreateAccounts",
"CanDeleteAccounts"
],
"nbf": 1662110501,
"exp": 1662111101,
"iss": "https://localhost:5000",
"aud": "http://localhost:8080"
}

直到我看到来自火星的@agua的评论(idk如何标记(,我才明白这项政策。RequireAssessation方法。

所以在我的行动中:

[HttpPost]
[Route(nameof(CreateAccount))]
[Authorize(Policy = Policies.CreateAccounts)] //string ref = "CreateAccountsPolicy"
public async Task<IActionResult> CreateAccount([FromBody] NewAccountRequest request)
{
// verify request data and create an account...
}

然后在Startup.cs

services.AddAuthorization(o =>
{
o.AddPolicy(Policies.CreateAccounts,
p => p.RequireAssertion(context => AssertClaim(context, Claims.CanCreateAccounts)));
});

最后有一个私有方法来验证一系列声明:

private static bool AssertClaim(AuthorizationHandlerContext context, string claim)
{
if (!context.User.HasClaim(c => c.Type == Claims.ClaimsString)) return false;
var claims = context.User.FindAll(x => x.Type == Claims.ClaimsString);
var correctClaim = claims.FirstOrDefault(x => x.Value == claim);
return correctClaim != null;
}

n.b.索赔和保单类只是自定义字符串引用

相关内容

  • 没有找到相关文章

最新更新