因此,我按照 Microsoft 文档开始了工作:
使用 Azure Active Directory 保护 ASP.NET Core Blazor WebAssembly 托管应用
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";
});
问题可能出在我的角色声明中。也许问题是这个声明看起来像一个数组?如果是这样,我该如何解决?