.Net9通过 IdentityServer4完成认证鉴权

张开发
2026/5/12 3:36:43 15 分钟阅读

分享文章

.Net9通过 IdentityServer4完成认证鉴权
gitee项目地址https://gitee.com/workRep/identity-server4-demo.git在 .NET 9 中虽然 IdentityServer4 已停止官方维护但其核心功能已由Duende IdentityServer​ 接管。对于 Web API 项目你需要分别配置认证服务器 (IdentityServer)​ 和受保护的 API 资源。以下是详细的集成步骤1. 认证服务器 (IdentityServer) 配置首先创建一个独立的 ASP.NET Core 项目作为认证服务器。1.1 安装 NuGet 包dotnet add package Duende.IdentityServer1.2 配置服务 (Program.cs)using Duende.IdentityServer.Models; var builder WebApplication.CreateBuilder(args); // 配置 IdentityServer builder.Services.AddIdentityServer() .AddInMemoryApiScopes(Config.ApiScopes) // 定义 API 范围 .AddInMemoryClients(Config.Clients) // 定义客户端 .AddDeveloperSigningCredential(); // 开发环境签名证书 var app builder.Build(); app.UseIdentityServer(); app.Run();1.3 定义配置类 (Config.cs)public static class Config { public static IEnumerableApiScope ApiScopes new ListApiScope { new ApiScope(api1, My API) }; public static IEnumerableClient Clients new ListClient { new Client { ClientId client, AllowedGrantTypes GrantTypes.ClientCredentials, //AllowedGrantTypes GrantTypes.ResourceOwnerPassword,//使用账户密码模式 ClientSecrets { new Secret(secret.Sha256()) }, AllowedScopes { api1 } } }; }2. Web API 资源服务器配置在你的 Web API 项目中配置 JWT Bearer 认证。2.1 安装 NuGet 包dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer2.2 配置认证 (Program.cs)var builder WebApplication.CreateBuilder(args); // 配置认证 builder.Services.AddAuthentication(Bearer) .AddJwtBearer(Bearer, options { options.Authority https://localhost:5001; // IdentityServer 地址 options.TokenValidationParameters new TokenValidationParameters { ValidateAudience false }; }); // 配置授权 builder.Services.AddAuthorization(options { options.AddPolicy(ApiScope, policy { policy.RequireAuthenticatedUser(); policy.RequireClaim(scope, api1); }); }); builder.Services.AddControllers(); var app builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();2.3 保护控制器在需要保护的控制器或方法上添加[Authorize]特性。[ApiController] [Route([controller])] [Authorize(Policy ApiScope)] // 应用授权策略 public class WeatherForecastController : ControllerBase { [HttpGet] public IActionResult Get() { return Ok(Protected data); } }3. 测试流程启动认证服务器运行 IdentityServer 项目通常在端口 5001。获取 Token使用 Postman 或 curl 向认证服务器请求 Token。curl -X POST https://localhost:5001/connect/token \ -H Content-Type: application/x-www-form-urlencoded \ -d client_idclientclient_secretsecretgrant_typeclient_credentialsscopeapi1访问 API将返回的access_token放在请求头中访问受保护的 API。Authorization: Bearer your_access_token4. 注意事项HTTPS 要求在生产环境中必须使用 HTTPS 并配置真实的签名证书替换AddDeveloperSigningCredential。数据持久化示例使用了内存配置 (InMemory)生产环境应使用数据库存储配置如AddConfigurationStore和AddOperationalStore。.NET 9 兼容性Duende IdentityServer 完全支持 .NET 9但需确保引用的包版本与 .NET 9 运行时兼容

更多文章