c# - ASP.Core 3 中基于角色的授权 : how to grant access everywhere to certain role?

标签 c# asp.net-core .net-core .net-core-3.0 abac

我正在编写一个ABAC系统,在其中我将决定用户是否可以根据某些角色/属性/等访问某些数据。但是,有一类特殊的用户(例如 super 管理员)应该能够随时随地访问所有内容。我不想检查所有策略、 Controller 、操作和方法并添加对此特定角色的检查。有没有办法以更集中的方式做到这一点? (例如:在启动中)。

如果不可能将其添加到全局位置,我正在考虑至少在 Controller 级别全局添加它:我正在寻找 here我看到装饰器 [Authorize(Roles = "Administrator")] 允许您将特定方法/类的访问权限限制为仅管理员用户。然而,我想要一种“相反”。我的意思是类似 AuthorizeAlways 的行为,具有以下行为:

[AuthorizeAlways(Roles = "SuperAdministrator")]
public class ControlPanelController : Controller
{
    [Authorize(Roles = "SetterUser")]
    public ActionResult SetTime()
    {
    }

    [Authorize(Roles = "PowerUser")]
    [MinimumAgeAuthorize(50)]
    public ActionResult ShutDown()
    {
    }
}

在这种情况下,我希望 super 管理员(即使他们已经 49 岁)可以访问任何地方。 SetterUser 只能访问 SetTime,只有 50 岁以上的 PowerUser 才能访问 ShutDown

我不知道这是否有意义。是否可以?我可以在哪里做呢?谢谢!

最佳答案

这篇博文提供了一个关于如何实现自定义授权的很好的教程: https://seanspaniel.wordpress.com/2019/12/13/custom-authorization-in-asp-net-core-3/

在该教程中,在 CustomAuthorizationMiddleware 类中,您可以检查“SuperAdministrator”角色并授予对每个端点的访问权限。

public static class CustomAuthorizationMiddleware
{
    public static async Task Authorize(HttpContext httpContext, Func next)
    {
        var endpointMetaData = httpContext.GetEndpoint().Metadata;

        bool hasCustomAuthorizeAttribute = endpointMetaData.Any(x => x is CustomAuthorizeAttribute);

        if (!hasCustomAuthorizeAttribute)
        {
            await next.Invoke();
            return;
        }

        CustomAuthorizeAttribute customAuthorizeAttribute = endpointMetaData
                .FirstOrDefault(x => x is CustomAuthorizeAttribute) as CustomAuthorizeAttribute;

        // Check if user has allowed role or super administrator role
        bool isAuthorized = customAuthorizeAttribute.AllowedUserRoles
            .Any(allowedRole => httpContext.User.IsInRole(allowedRole)) 
             || httpContext.User.IsInRole("SuperAdministrator");

        if (isAuthorized)
        {
            await next.Invoke();
            return;
        }

        httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        await httpContext.Response.WriteAsync("unauthorized");
    }
}

关于c# - ASP.Core 3 中基于角色的授权 : how to grant access everywhere to certain role?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59374087/

相关文章:

c# - .net 核心中的单元测试 Url.Link

c# - 在 .net 核心 Web api 和 Angular 6 中启用 CORS

c# - MoveNext 的前缀在堆栈中意味着什么?

c# - 计算GDI+绘图的边界框

asp.net-core - 绑定(bind)到 Blazor 中的 ExpandoObject

c# - *.json 文件更改后 IOptionsSnapshot 不刷新

linux - .NET Core - 为什么 AsyncLocal<> 引用构建在 Windows 而不是 Linux (netstandard2.0)

c# - 减少 LambdaExpression 签名

dependency-injection - 将身份验证从 dotnet core 1.1 迁移到 dotnet core 2.0

c# - NET Core 类库读取项目文件夹中的文件