.NET Core IdentityServer4 入门与 API 添加客户端凭据

夏日蝉鸣 2024-02-17 ⋅ 21 阅读

引言

在现代的软件开发中,身份认证和授权是不可或缺的一部分。为了实现安全的用户认证和授权机制,很多公司和开发者选择使用 IdentityServer4 这个强大的身份认证和单点登录解决方案。

本文将介绍如何入门使用 .NET Core IdentityServer4,并演示如何为 API 添加客户端凭据,以实现对 API 的安全保护。

什么是 IdentityServer4?

IdentityServer4 是一个开源的身份验证和授权服务器,是使用 ASP.NET Core 实现的。它可以让开发者轻松地添加身份认证和授权功能到他们的应用程序中。通过 IdentityServer4,我们可以集中管理和控制用户对受保护资源的访问。

准备工作

在开始之前,确保你已经安装了以下环境:

创建一个新的 .NET Core 项目

首先,打开终端并创建一个新的空文件夹:

mkdir IdentityServer4Tutorial
cd IdentityServer4Tutorial

然后,使用以下命令创建一个新的 .NET Core 项目:

dotnet new webapi -o IdentityServer4Demo

进入项目所在的目录:

cd IdentityServer4Demo

添加 IdentityServer4 到项目中

在 Visual Studio Code 中打开 Startup.cs 文件,并添加以下代码到 ConfigureServices 方法中:

services.AddIdentityServer()
    .AddInMemoryClients(new List<Client>())
    .AddInMemoryIdentityResources(new List<IdentityResource>())
    .AddInMemoryApiResources(new List<ApiResource>())
    .AddInMemoryApiScopes(new List<ApiScope>())
    .AddDeveloperSigningCredential();

现在,我们已经成功地将 IdentityServer4 添加到了我们的项目中。

添加一个客户端和资源

ConfigureServices 方法中的 .AddInMemoryClients(new List<Client>()) 行下面,添加以下代码:

var clients = new List<Client>
{
    new Client
    {
        ClientId = "client1",
        ClientSecrets = { new Secret("secret1".Sha256()) },
        AllowedGrantTypes = GrantTypes.ClientCredentials,
        AllowedScopes = { "api1" }
    }
};
services.AddInMemoryClients(clients);

var apiResources = new List<ApiResource>
{
    new ApiResource("api1", "API 1")
};
services.AddInMemoryApiResources(apiResources);

以上代码添加了一个名为 "client1" 的客户端和一个名为 "api1" 的资源。

添加认证中间件

打开 Configure 方法,在 .UseRouting() 的下一行添加以下代码:

app.UseAuthentication();

然后,在 .UseAuthentication() 方法的下一行添加以下代码:

app.UseAuthorization();

运行项目

现在,我们已经完成了 IdentityServer4 的配置。使用以下命令运行项目:

dotnet run

打开浏览器并访问 https://localhost:5001/.well-known/openid-configuration,你将能够看到 IdentityServer4 的元数据信息。

测试客户端凭据

如果一切正常,我们现在可以开始测试我们的 IdentityServer4。首先,我们需要获取一个访问令牌。

使用以下命令通过 client_credentials 授权模式获取访问令牌:

curl --location --request POST 'https://localhost:5001/connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=client1' \
--data-urlencode 'client_secret=secret1' \
--data-urlencode 'scope=api1' \
--data-urlencode 'grant_type=client_credentials'

你将会在响应中得到一个访问令牌。使用这个访问令牌调用你的 API,以确保它受到身份验证和授权的保护。

结论

通过本文,我们了解到了如何入门使用 .NET Core IdentityServer4,并成功为 API 添加了客户端凭据。IdentityServer4 提供了一个强大且灵活的身份验证和授权解决方案,可以帮助我们轻松地保护我们的应用程序和 API。希望本文能为你提供有关 IdentityServer4 的初步了解,并帮助你为你的应用程序增加安全性。

如果你想深入了解 IdentityServer4,可以查看其官方文档:IdentityServer4 Documentation

Happy coding!


全部评论: 0

    我有话说: