首页 > 解决方案 > 如何将 Azure AD 身份验证与 .net core mvc 中的自定义角色存储集成?

问题描述

我有使用 .net core mvc 创建的 Web 应用程序,并启用了 azure AD 身份验证,并且有带有角色和用户表的 postgress 数据库。

Startup.cs如下

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

        ValidateToken(services);

        services.AddControllersWithViews(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        });

        services.AddRazorPages();

        //ConfigureElsa(services);

        ConfigureDatabaseContext(services);
        ConfigurePolicies(services);
        ConfigureHandlers(services);
    }

我已经在 azure 门户中注册了应用程序,一切正常。

我需要知道如何将它与我现有的数据库角色集成。

有人可以帮助我吗?

谢谢

标签: azure-active-directoryasp.net-core-mvcazure-web-app-serviceasp.net-core-3.1

解决方案


看起来最适合您的方案的是 Azure 广告中的应用角色功能。这是一个示例,它演示了如何定义角色以及如何使用 asp.net 核心类中的属性来根据角色声明执行 AuthZ。您可以利用 MS Graph API 的应用程序补丁端点来动态添加应用程序角色。只需编写一个实用程序来从本地角色数据库导入应用程序角色,然后点击端点以使用新的应用程序角色修补您的应用程序注册。这是一个示例补丁请求。

URL https://graph.microsoft.com/v1.0/applications/3e7d226f-2c9b-4d28-b3ce-6a9353753hah

{
    "appRoles": [
        {
            "allowedMemberTypes": [
                "User",
                "Application"
            ],
            "description": "TestRole",
            "displayName": "TestRole",
            "id": "6cd9c306-9252-4092-b52a-960016053356",
            "isEnabled": true,
            "origin": "Application",
            "value": "TestRoles"
        }
    ]
}

请注意,以下是权限要求。 在此处输入图像描述

以下 PowerShell 脚本将使您能够在现有应用程序注册中创建应用程序角色

Connect-AzureAD -TenantId <TenantId>
# Create an Azure AD role of given name and description
Function CreateAppRole([string] $Name, [string] $Description)
{
$appRole = New-Object Microsoft.Open.MSGraph.Model.AppRole
$appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
$appRole.AllowedMemberTypes.Add(“User”);
$appRole.AllowedMemberTypes.Add(“Application”);
$appRole.DisplayName = $Name
$appRole.Id = New-Guid
$appRole.IsEnabled = $true
$appRole.Description = $Description
$appRole.Value = $Name;
return $appRole
}
# ObjectId for application from App Registrations in your AzureAD
$appObjectId = “&lt;ObjectId>”
$app = Get-AzureADMSApplication -ObjectId $appObjectId
$appRoles = $app.AppRoles
Write-Host “App Roles before addition of new role..”
Write-Host $appRoles
$newRole = CreateAppRole -name “NewApplicationName” -description “New application description”
$appRoles.Add($newRole)
Set-AzureADMSApplication -ObjectId $app.Id -AppRoles $appRoles

如果此解决方案对您有帮助,请将其标记为已验证。


推荐阅读