使用 identityserver4 保护多个 API

Securing multiple Apis using identityserver4

我想只使用一个 identityserver4 应用程序来保护我的所有 API。

我的第一个资源 api 和客户端应用程序:

我的第二个资源api 和应用程序:

我的其他资源api 和应用程序:

我只想创建一个 IdentityServer4 并保护我的资源(DashboardApi、HumanResourceApi、CustomerManagementApi),我想将我的客户端应用程序保存在相同的 IdentityServer4 应用程序上。

这可能吗?我应该在 identityserver 上创建不同的 ApiResources 和 Scopes 吗?我该怎么做?

是的,这是可能的,因为 IdentityServer4 使您能够定义资源 API、客户端应用程序、用户、范围,并且您可以使用内存数据配置这些数据以进行初始测试,甚至可以使用 Entity Framework 等其他存储机制来配置这些数据例如。

这里解释起来并不简单,但是在官方documentation中有一些快速入门,你可以做一下以了解更多。

您可以在上面看到一些资源 API、客户端应用程序、内存中的用户的配置示例(使用 Config.cs class)只是为了让您了解如何简单地开始:

Resource Apis:客户想要访问的受保护的api

   public static IEnumerable<ApiResource> GetApis()
   {
        return new List<ApiResource>
        {
            new ApiResource("CustomerManagementApi", "My CustomerManagementApi"),
            new ApiResource("DashboardApi", "My DashboardApi"),
            // others ...
        };
   }

客户端:想要访问资源 API 的应用程序

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        new Client
        {
            ClientId = "client",

            // no interactive user, use the clientid/secret for authentication
            AllowedGrantTypes = GrantTypes.ClientCredentials,

            // secret for authentication
            ClientSecrets =
            {
                new Secret("secret".Sha256())
            },

            // scopes that client has access to
            AllowedScopes = { "CustomerManagementApi" }
        }
    };
}

用户:想要访问某些资源的最终用户

public static List<TestUser> GetUsers()
{
    return new List<TestUser>
    {
        new TestUser
        {
            SubjectId = "1",
            Username = "alice",
            Password = "password"
        },
        new TestUser
        {
            SubjectId = "2",
            Username = "bob",
            Password = "password"
        }
    };
}