.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.IdentityServer
1.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 IEnumerable<ApiScope> ApiScopes =>
        new List<ApiScope>
        {
            new ApiScope("api1", "My API")
        };

    public static IEnumerable<Client> Clients =>
        new List<Client>
        {
            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.JwtBearer
2.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. 测试流程

  1. 启动认证服务器:运行 IdentityServer 项目(通常在端口 5001)。

  2. 获取 Token:使用 Postman 或 curl 向认证服务器请求 Token。

    复制代码
    curl -X POST "https://localhost:5001/connect/token" \
         -H "Content-Type: application/x-www-form-urlencoded" \
         -d "client_id=client&client_secret=secret&grant_type=client_credentials&scope=api1"
  3. 访问 API :将返回的 access_token放在请求头中访问受保护的 API。

    复制代码
    Authorization: Bearer <your_access_token>

4. 注意事项

  • HTTPS 要求 :在生产环境中,必须使用 HTTPS 并配置真实的签名证书(替换 AddDeveloperSigningCredential)。

  • 数据持久化 :示例使用了内存配置 (InMemory),生产环境应使用数据库存储配置(如 AddConfigurationStoreAddOperationalStore)。

  • .NET 9 兼容性:Duende IdentityServer 完全支持 .NET 9,但需确保引用的包版本与 .NET 9 运行时兼容

相关推荐
2601_962072551 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
步步为营DotNet2 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
咸鱼翻身小阿橙2 天前
VS2008 + .NET3.5 环境、加热台TCP通讯场景
tcp/ip·php·.net
tonydf2 天前
DotNet项目接入Copilot SDK简单案例
后端·.net·github copilot
ABprogramming2 天前
Aspire入门指南
c#·.net
User_芊芊君子2 天前
鸿蒙PC适配:Pinta GTK 图像编辑器鸿蒙 PC ArkWeb 适配全记录:从 .NET_GTK4 桌面到 HarmonyOS PC HAP
编辑器·.net·harmonyos
ServBay3 天前
你跟高级 C# 工程师的区别,就是这8个开发技巧
后端·c#·.net
小满Autumn3 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
ceclar1234 天前
C# 的任务并行库(TPL)
开发语言·c#·.net