簡體   English   中英

ASP.NET 核心授權不適用於嵌套角色

[英]ASP.NET Core authorization not working for nested roles

我在 ASP.NET 核心項目中實現了基於角色的訪問控制 (RBAC)。 我要求用戶至少屬於一個 Active Directory 角色,具體取決於代碼部署到的環境(DEV、STAGING、PROD)。 下面的代碼有效。 但是,我現在需要使用單個“嵌套”/分組/分層角色,即新角色將其他角色組合在一起,而不是在每個環境中使用多個角色。 使用新的 AD 角色不再有效。 我已確認我是新角色的成員,但我收到授權錯誤。 我在網上找不到任何討論是否可以在 ASP.NET 核心中使用分組角色的內容。

public void ConfigureServices(IServiceCollection services)
{
    try
    {
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddMvc().AddApplicationPart(typeof(ProcessController).Assembly).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddRequestScopingMiddleware(() => _scopeProvider.Value = new Scope());
        services.AddCustomControllerActivation(Resolve);
        services.AddCustomViewComponentActivation(Resolve);

        services.AddAuthorization(options =>
        {
            var policyBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
            switch (HostingEnvironment.EnvironmentName)
            {
                case "Development":
                    policyBuilder.RequireRole("roleA", "roleB");
                    //policyBuilder.RequireRole("roleAandB");//this doesn't work
                    break;
                case "Staging":
                    policyBuilder.RequireRole("roleC", "roleD");
                    break;
                case "Production":
                    policyBuilder.RequireRole("roleE", "roleF");
                    break;
                default:
                    policyBuilder.RequireRole("roleG");
                    break;
            }

            options.AddPolicy("Environment", policyBuilder.Build());
        });

    }
    catch (Exception e)
    {
        _logger.Error(e, "Unhandled exception");
        throw;
    }
}

[Authorize(Policy = "Environment")]
public class ProcessController : ControllerBase 
{
    ...
}

如何在 ASP.NET 核心授權中使用嵌套角色?

ASP.NET 中所謂的“角色”對應於 Active Directory 中的組。 因此,檢查 AD 用戶是否具有角色實際上是檢查用戶是否在組中。

假設您想授予“高級用戶”訪問網站某個部分的權限。 您將在 AD 中創建一個名為MyAppPowerUsers的組,並將其用作應用程序中的角色:

policyBuilder.RequireRole("MyAppPowerUsers");

然后,您將您認為是“高級用戶”的任何人添加到 AD 中的該組。 例如,如果您想授予所有經理和團隊主管訪問您網站的“超級用戶”部分的權限,那么您創建名為ManagersTeamLeads的組並將其添加到MyAppPowerUsers

在這種情況下,任何屬於ManagersTeamLeads成員的用戶都將被視為MyAppPowerUsers的成員。

所以這個想法是,在大多數情況下,你:

  • 在應用程序中創建一個以角色命名的組
  • 為職位描述創建組。 例如,您甚至可能已經將這些作為分發列表(只要這些 DL 具有“安全”的“組類型”)
  • 將職位描述組添加到角色

當然,如果您想將一個人添加到一個角色中,而不是所有具有其職位描述的人,則可能會有例外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM