【问题标题】:Can't Get Blazor WASM AAD App Roles To Work无法让 Blazor WASM AAD 应用角色工作
【发布时间】:2020-10-29 22:06:28
【问题描述】:

所以我已经开始关注 Microsoft 文档:

Secure an ASP.NET Core Blazor WebAssembly hosted app with Azure Active Directory

Azure AD Groups, Administrative Roles, and user-defined roles

在 Azure 方面似乎设置得很好:

这很好用:

@page "/clients"
@inject NavigationManager navigationManager
@inject HttpClient Http
@inject AppData appData
@inject AuthenticationStateProvider AuthenticationStateProvider
@attribute [Authorize]

我已经打印了声明以查看发生了什么:

protected async override Task OnInitializedAsync()
{
    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;

    foreach (var claim in user.Claims)
    {
            System.Diagnostics.Debug.WriteLine(claim.Type + ":" + claim.ValueType + ":" + claim.Value);
    }
}

这是打印的行之一:

roles:http://www.w3.org/2001/XMLSchema#string:["Admin"]

所以我可以看到我在 Azure 上的应用清单中添加的 appRole 到了这里。 (出于隐私考虑,GUID 隐藏在下方)

"appRoles": [
        {
            "allowedMemberTypes": [
                "User"
            ],
            "description": "Can view everything.",
            "displayName": "Global Viewer",
            "id": "IDGOESHERE",
            "isEnabled": true,
            "lang": null,
            "origin": "Application",
            "value": "GlobalViewer"
        },
        {
            "allowedMemberTypes": [
                "User"
            ],
            "description": "Admins can access restricted areas.",
            "displayName": "Admin",
            "id": "IDGOESHERE",
            "isEnabled": true,
            "lang": null,
            "origin": "Application",
            "value": "Admin"
        }
    ],

还将我的用户添加到企业应用程序的管理员角色。

但是在 [Authorize] 属性指令中添加角色会使我无法访问页面:(您无权访问此资源。)

attribute [Authorize(Roles = "Admin")]

这是在 Program.cs 中(我在“GUIDGOESHERE”中有实际的 GUID)

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("GUIDGOESHERE/EmployeesAccess");
    options.ProviderOptions.DefaultAccessTokenScopes.Add("GUIDGOESHERE/AdminAccess");
    options.UserOptions.RoleClaim = "roles";
});

问题可能出在我的角色声明中。也许问题是这个声明看起来像一个数组?如果是这样,我该如何解决?

【问题讨论】:

    标签: c# asp.net-core authentication roles blazor-webassembly


    【解决方案1】:

    原来 Azure 可能比 ASP.NET Core 稍微领先一点

    Azure AD 身份验证默认模板无法开箱即用,需要稍作调整。

    在此处按照 MS 文档中的步骤操作:Azure AD Groups, Administrative Roles, and user-defined roles

    长话短说:

    • 它开箱即用,只有一个角色。例如“管理员”
    • 问题在于拥有多个角色。
    • “角色”声明以字符串“[Admin,User]”的形式到达,该字符串与“Admin”或“User”不匹配
    • CustomUserAccount 类将角色分解为一个 string[] 对象,从而解决了问题。
    • Microsoft 在记录解决方法方面做得很好。 (以上链接)

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2021-10-22
      • 2021-05-30
      • 2021-07-20
      • 2021-05-14
      • 2021-04-07
      • 1970-01-01
      • 2021-11-06
      • 2021-04-13
      相关资源
      最近更新 更多