ASP.NET Core的身份认证框架IdentityServer4--(1)服务配置

2022-11-16,,,,

官网文档地址:点我点我

项目实例源码地址

准备

创建一个名为IdentityServer的ASP.NET Core Web Api 项目,端口5000

创建一个名为Api的ASP.NET Core Web Api 项目,端口5001

创建一个名为Web的应用程序,端口5002

基本配置

首先创建一个新的ASP.NET Core项目。

然后选择“空白”选项。

注:这里创建空的应用程序是为了后面方便引入UI界面

接下来,使用nuget添加IdentityServer4

或者,也可以使用软件包管理器控制台通过运行以下命令来添加依赖项

Install-Package IdentityServer4

IdentityServer中使用通常的模式来配置和添加服务到ASP.NET Core Host

ConfigureServices中,所有的服务必须配置并且依赖注入到系统中。

Configure中,中间件被添加到HTTP管道中。

public void ConfigureServices(IServiceCollection services)
{
//配置身份服务器与内存中的存储,密钥,客户端和资源
services.AddIdentityServer().AddDeveloperSigningCredential();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//添加到HTTP管道中。
app.UseIdentityServer(); app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}

AddIdentityServer方法在依赖注入系统中注册IdentityServer,它还会注册一个基于内存存储的运行时状态,这对于开发场景非常有用,对于生产场景,您需要一个持久化或共享存储,如数据库或缓存。

扩展的AddDeveloperSigningCredential用于签署令牌创建临时密钥。

修改hosting

修改启动端口,打开Properties下的launchSettings.json修改applicationUrl中的端口改为5000,注:这里修改启动端口是为了方便调试

使用客户端凭证保护API

在这种情况下,我们将定义一个API和一个想要访问它的客户端。客户端将在IdentityServer上请求访问令牌,并使用它来访问API。

IdentityServer项目中新建个Config.cs类,并添加以下代码:

/// <summary>
/// 定义api信息
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
psApiResource类为IdentityServer中的实体类,这里引用IdentityServer4.Models命名空间即可。

定义客户端

定义一个可以访问这个API的客户端。对于这种情况,客户端将不具有交互式用户,并将使用IdentityServer的所有客户端密钥进行身份验证。在Config.cs中添加如下代码:

public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
//没有交互式用户,使用clientid / secret进行身份验证
AllowedGrantTypes = GrantTypes.ClientCredentials,
//秘密认证
ClientSecrets =
{
new Secret("secret".Sha256())
},
//客户端可以访问的范围
AllowedScopes = {"api1"}
}
};
}

注册IdentityServer服务

要配置IdentityServer以便使用定义好的访问控制,您需要向该ConfigureServices方法添加代码。您可以使用方便的扩展方法 ,将相关的存储和数据添加到DI系统中:

public void ConfigureServices(IServiceCollection services)
{
//配置身份服务器与内存中的存储,密钥,客户端和资源
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())//添加api资源
.AddInMemoryClients(Config.GetClients());//添加客户端
}

运行项目并在浏览器中访问:http://localhost:5000/.well-known/openid-configuration,可以看到所有的文档。这将被您的客户端和API用于下载必要的配置数据。

  

ASP.NET Core的身份认证框架IdentityServer4--(1)服务配置的相关教程结束。

《ASP.NET Core的身份认证框架IdentityServer4--(1)服务配置.doc》

下载本文的Word格式文档,以方便收藏与打印。