C# .NET Core Hosted Blazor WebAssembly - 向 .Server 项目添加额外的客户端 API

C# .NET Core Hosted Blazor WebAssembly - Add additional clients to .Server project API

我有一个 .NET Core 托管的 Blazor WebAssembly 应用程序,来自使用 Microsoft.AspNetCore.ApiAuthorization.IdentityServer 包的默认 Microsoft 模板。

我需要添加一个单独的客户端来通过客户端凭据请求访问令牌,以便在服务器端应用程序上使用 API 控制器端点,但在 Microsoft 网站上找不到任何关于如何注册它们的文档或 IdentityServer4 文档,因为它使用的是 Microsoft 的实现。

我已经尝试在单独的 Config.cs 文件中注册客户端,就像您在典型的 IdentityServer4 项目中所做的那样:

public static IEnumerable<IdentityServer4.Models.Client> Clients =>
        new List<IdentityServer4.Models.Client>
        {
            new IdentityServer4.Models.Client
            {
                ClientId = "web_id",
                ClientSecrets = { new Secret("web_id".ToSha256()) },
                AllowedGrantTypes = GrantTypes.ClientCredentials,
                AllowedScopes = { "WebAssemblyTest.ServerAPI" }
            }
        };

启动:

services.AddIdentityServer()
            .AddInMemoryClients(Config.Clients)
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

然而,这个 returns 客户端在请求令牌时未发现错误:

根据 Microsoft Blazor WebAssembly docs,API 资源:"WebAssemblyTest.ServerAPI" 在启动时使用 AddIdentityServerJwt() 注册,所以我不知道如何让它工作.

由此 我能够以这种方式加载我的附加客户端配置:

services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
                {
                    options.Clients.Add(new IdentityServer4.Models.Client
                    {
                        ClientId = "web_id",
                        ClientSecrets = { new Secret("web_id".ToSha256()) },
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                        AllowedScopes = { "WebAssemblyTest.ServerAPI" }

                    });
                });

如答案所述:"ASP.NET Identity overrides the documented method for IdentityServer Clients configuration" 因此您必须将 IdentityServer4.Models.Client 的单个或数组直接传递到 .AddApiAuthorization() 方法中。