IdentityServer4:调用 web api 时观众为空?

IdentityServer4: audience is empty when calling web api?

IdentityServer4 v4,当通过 Web Blazor 客户端应用程序调用 Web api 时发生错误。

Bearer error="invalid_token", error_description="The audience 'empty' is invalid" value in header 

scope是这样在startup中添加的,如何添加audience?

            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                options.ClientId = "testapp";
                options.ResponseType = "code";
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.UseTokenLifetime = false;
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("offline_access");
                options.Scope.Add("account");
                options.Scope.Add("accountwrite");
                options.Scope.Add("accountread");
                options.Scope.Add("payment");
                options.Scope.Add("paymentwrite");
                options.Scope.Add("paymentread");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                };
                options.Events = new OpenIdConnectEvents
                {
                    OnAccessDenied = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/");
                        return Task.CompletedTask;
                    }
                };
            });

仅当您在 IdentityServer 中定义了 ApiScopes 和 ApiResources 时才会填充受众声明。

一个API范围可以定义为:

new ApiScope(name: "invoice",
        displayName: "Invoices access",
        userClaims: new List<string> { "level" }),

要定义合适的 ApiResource,您可以通过以下方式定义:

_apiResources = new List<ApiResource>()
{
    new ApiResource("invoiceapi")
    {
        Scopes = { "invoice" }   //invoice is the name of the ApiScope
    }
};

那你需要在你的客户端询问发票范围。