WebAssembly Razor 客户端应用程序 return 401 在 Azure 中使用管理员角色调用受保护的 API

WebAssembly Razor client app return 401 while calling a protected API in Azure with Admin Role

我有 API 受 Azure AD 保护,其中需要身份验证才能获取访问数据,我现在只使用一个简单的范围公开 API。

API 和客户端应用程序都已在 Azure AD 中注册。 还为 API 配置了角色,只有具有 Admin 角色的用户才能调用我的 API.

我是否需要将此管理员角色也分配给客户端应用程序?或 AccessApi 范围是否足够?

Scopes  Who can consent     Admin consent display name     User consent display name   State 

api://xx  User              AccessApi                      AccessApi                 Enable

并且使用 webassembly blazor 构建的客户端应用程序也在 Azure AD 中注册,并且其配置为 Api permission 以使用 delegated 访问 AccessApi

API / Permissions name  Type       Description   Admin consent required    Status
myApi (1)   

AccessApi              Delegated     AccessApi              No

我配置 webassembly blazor 客户端应用程序以针对 azure 进行身份验证并获取令牌并使用该令牌调用 myApi,但是我一直收到 loading 但没有任何数据显示错误。

我不确定这里出了什么问题?

program class 客户端应用程序:

 private static string scope = @"api://xxx/AccessApi";

...

            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");


            builder.Services.AddScoped<GraphAPIAuthorizationMessageHandler>();

            builder.Services.AddHttpClient("ServerAPI",
                client => client.BaseAddress = new Uri("https://localhost:44314"))
                .AddHttpMessageHandler<GraphAPIAuthorizationMessageHandler>();

            builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
                .CreateClient("ServerAPI"));

            builder.Services.AddMsalAuthentication(options =>
            {
                builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                options.ProviderOptions.DefaultAccessTokenScopes.Add(scope);
            });

fetch data razor page 我导入了所有必要的库

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject IAccessTokenProvider TokenProvider
@attribute [Authorize]

@inject NavigationManager UriHelper
@inject HttpClient Http

...

data = await Http.GetFromJsonAsync<data[]>(@"API-url--runs-locally-on-docker");

授权消息处理程序class

 private static string scope = @"api://xxx/AccessApi";
    public GraphAPIAuthorizationMessageHandler(IAccessTokenProvider provider,
        NavigationManager navigationManager)
        : base(provider, navigationManager)
    {
        ConfigureHandler(
            authorizedUrls: new[] { "https://localhost:44314" },
            scopes: new[] { scope });
    }

使用 Azure AD 帐户对自己进行身份验证后,客户端应用程序显示 loading.. 但没有显示任何数据。 在控制台级别显示此错误。

Failed to load resource: the server responded with a status of 401 (Unauthorized)

我遵循了 Microsoft 文档,但我不确定我在这里遗漏了什么。 这里可能出了什么问题?

更新

Api 公开选项卡:

客户端应用程序的

Api 权限:

显然,您的 scope 设置不正确。您应该将范围设置为 api 应用程序 的客户端 ID,而不是客户端应用程序的客户端 ID。在你的问题中,我认为你的范围应该是:api://7b4d6df9-63cd-4ed7-881bxxx/AccessApi.

解析令牌,您应该会看到 scp 声明和 roles 声明。