如何在aspnet core代码中验证用户策略?

问题描述 投票:0回答:2

我见过的所有教程都向您展示了如何通过添加来保护操作

[Authorize(Policy = "admin")]

控制器或动作。

但是,如果某人是“管理员”,我需要向浏览器返回问题的答案(以 json 格式),而不是抛出错误 并且没有任何消息来源告诉我们如何做到这一点。 是的,您可以检查索赔 (User.HasClaim),但保单由多个索赔组成。

那么我该怎么做呢?

asp.net-core asp.net-core-mvc
2个回答
41
投票

在控制器的构造函数中,您可以依赖 IAuthorizationServiceauthorizationService 来注入它。然后您可以使用它来检查用户是否符合这样的策略:

var isAuthorized = await authorizationService.AuthorizeAsync(User, "admin");

其中“admin”是策略的名称


0
投票

首先,让我这样说:接受的答案是执行此操作的正确方法。在控制器的构造函数中注入

IAuthorizationService
,然后调用此:

var isAuthorized = await authorizationService.AuthorizeAsync(User, "admin"); // where admin = policy name

但在我的项目中我最终使用了不同的解决方案。因为我需要在 getter 中检查

isAuthorized
AuthorizeAsync
是异步的,C# 中不允许使用异步属性。这是我的解决方案:

我写了一个 ClaimsPrincipalExtension:

public static class ClaimsPrincipalExtension
{
    public static bool IsAdminPolicyAuthorized(this ClaimsPrincipal? user)
    {
        if (user is null) return false;

        var allConditionsMet = false;

        // check all the claims and conditions you want to check
        // ...
        // allConditionsMet = your code goes here
        // ...
        
        return allConditionsMet;
    }
}

AuthorizationHandler
内,我只需拨打分机号:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AdminAuthorizedRequirement requirement)
{
    var isAuthorized = context.User.IsAdminPolicyAuthorized();
    if (isAuthorized) context.Succeed(requirement);

    return Task.CompletedTask;
}

现在我可以在任何需要的地方调用分机,如下所示:

var isAuthorized = User.IsAdminPolicyAuthorized();
© www.soinside.com 2019 - 2024. All rights reserved.