practical-aspnetcore 实战:在 ASP.NET Core 最小 API 中实现简化的 JWT Bearer 令牌认证

原创2026-10-14 18:58:561,068 阅读
文章标签:示例工程

practical-aspnetcore 实战:在 ASP.NET Core 最小 API 中实现简化的 JWT Bearer 令牌认证

本篇文章基于 practical-aspnetcore 仓库中 authentication-1 示例文档 及其完整的 Program.cs 实现,系统讲解如何在 ASP.NET Core 最小 API(Minimal API)中,用 builder.AddAuthentication().AddJwtBearer() 这一“简化”API 一步完成 JWT Bearer 身份认证与授权配置。你将掌握认证/授权管线(AddAuthentication → AddAuthorization → UseAuthorization → RequireAuthorization)的搭建顺序、TokenValidationParameters 各校验开关的含义、对称密钥签名 JWT 的签发方法,以及前端携带 Authorization: Bearer <token> 访问受保护接口的完整闭环。

示例背景:authentication 系列的第一个 JWT 样例

在 practical-aspnetcore 仓库中,认证相关示例统一收录在 projects/authentication/readme.md 下,共包含 5 个递进式样例:

示例目录 主题
authentication-1 简化 JWT Bearer 令牌认证(最小 API,显式配置 TokenValidationParameters)
authentication-2 Cookie 认证(builder.AddAuthentication().AddCookie())
authentication-3 同一应用中同时使用 JWT 与 Cookie 两种认证方案
authentication-4 Web API 模板 + 内置 OpenAPI 的极简 JWT 认证
authentication-5 使用 Identity API 端点 + Entity Framework Core 的完整认证

authentication-1 是本系列的起点,文档核心只有一句话:展示通过 builder.AddAuthentication().AddJwtBearer() 实现简化认证与授权。这句话的完整技术内涵全部落在同目录的 Program.cs 中,是一个结构精炼、可直接运行的端到端示例:签发 JWT → 携带令牌访问受保护接口 → 校验通过后返回用户信息。

该示例基于 .NET 10,从 authentication-1.csproj 可以看到目标框架为 net10.0,并引用了 Microsoft.AspNetCore.Authentication.JwtBearer 10.0.11 包;仓库根目录的 global.json 指定 SDK 版本为 10.0.0(rollForward: major,允许预发布版)。

认证与授权的完整配置链路

示例的配置代码极其紧凑,全部集中在 Program.cs 中:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthorization();
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
    options.IncludeErrorDetails = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "practical aspnetcore",
        ValidAudience = "https://localhost:5001/",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is custom key for practical aspnetcore sample"))
    };});

var app = builder.Build();

app.UseAuthorization();

这段代码揭示了一条清晰的四步管线,顺序不能颠倒:

  1. builder.Services.AddAuthorization():注册授权服务(IAuthorizationService、策略与 [Authorize]/RequireAuthorization 的支持设施)。
  2. builder.Services.AddAuthentication(options => ...):注册认证服务,并把 JwtBearerDefaults.AuthenticationScheme(值为字符串 "Bearer")同时设置为 默认认证方案(DefaultAuthenticateScheme)与 默认质询方案(DefaultChallengeScheme)。前者决定“如何识别当前用户”,后者决定“未认证时如何要求登录”。
  3. .AddJwtBearer(options => ...):向管线注册 JWT Bearer 处理器,并配置令牌校验参数。
  4. app.UseAuthorization():把授权中间件挂入请求管线。注意这里没有显式调用 UseAuthentication()——当认证方案已注册且被使用时,UseAuthorization 之前的认证中间件会在请求管线中按默认方案自动执行令牌解析。

这是 ASP.NET Core 认证体系的经典用法:注册(Register)→ 认证(Authenticate)→ 授权(Authorize)。相比老式写法,builder.AddAuthentication().AddJwtBearer() 的可链式调用正是文档标题中“simplified”(简化)二字的含义。

AddJwtBearer 配置与 TokenValidationParameters 逐项拆解

AddJwtBearer 的回调参数承载了所有令牌校验逻辑,下面按源码逐项说明:

.AddJwtBearer(options => {
    options.IncludeErrorDetails = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,        // 校验 iss(签发方)是否与 ValidIssuer 一致
        ValidateAudience = true,      // 校验 aud(受众)是否与 ValidAudience 一致
        ValidateLifetime = true,      // 校验 exp(过期时间),过期令牌直接拒绝
        ValidateIssuerSigningKey = true, // 校验签名密钥是否可信
        ValidIssuer = "practical aspnetcore",
        ValidAudience = "https://localhost:5001/",
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes("this is custom key for practical aspnetcore sample"))
    };
});

各配置项的作用与取值要点:

配置项 作用 示例取值说明
IncludeErrorDetails 认证失败时是否在响应中附带详细错误信息 示例设为 true,便于调试;生产环境通常建议关闭
ValidateIssuer 开启签发方校验 配合 ValidIssuer 使用,必须与令牌 iss 声明完全一致
ValidateAudience 开启受众校验 配合 ValidAudience 使用,必须与令牌 aud 声明完全一致
ValidateLifetime 校验令牌有效期 依赖令牌中的 nbf(生效时间)与 exp(过期时间)声明
ValidateIssuerSigningKey 校验签名密钥 配合 IssuerSigningKey 使用,防令牌被伪造
ValidIssuer 期望的签发方标识 示例为 "practical aspnetcore"
ValidAudience 期望的受众标识 示例为 "https://localhost:5001/"
IssuerSigningKey 用于验签的对称密钥 示例用 UTF-8 字节构造 SymmetricSecurityKey

值得强调的是 IssuerSigningKey 的对称性设计:签发与验签使用同一个密钥。示例在“验签”配置(第 25 行)和“签发”方法(Program.cs 第 80 行)中分别用完全相同的字符串 "this is custom key for practical aspnetcore sample" 构造了 SymmetricSecurityKey,这正是 JWT 能通过 ValidateIssuerSigningKey 校验的前提——若两处密钥不一致,服务端将无法解开令牌签名,认证必然失败。同时这也提醒我们:示例中的明文硬编码密钥仅用于教学演示,真实项目中应通过配置中心、环境变量或密钥管理服务(如 Azure Key Vault)安全托管。

签发 JWT:GenerateJSONWebToken 实现拆解

仅配置好服务端还不够,必须能生成合法令牌才能演示完整闭环。示例用顶层局部函数 GenerateJSONWebToken()(Program.cs)完成签发:

string GenerateJSONWebToken()
{
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is custom key for practical aspnetcore sample"));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(issuer:"practical aspnetcore",
        audience:"https://localhost:5001/",
        claims: new List<Claim>
        {
            new Claim(ClaimTypes.Name, "Anne"),
        },
        notBefore: null,
        expires: DateTime.Now.AddMinutes(120),
        signingCredentials: credentials);

    return new JwtSecurityTokenHandler().WriteToken(token);
}

签发过程的四个关键点:

  1. 签名算法:SigningCredentials 使用 SecurityAlgorithms.HmacSha256(HS256),与服务端验签配置完全对应——对称密钥 + HMAC-SHA256 是最常见的单机/单体场景签名方式。
  2. 声明(Claims):注入 ClaimTypes.Name 值为 "Anne" 的身份声明。该声明会被映射为 user.Identity.Name,在受保护端点中被直接读取。
  3. 有效期:expires 设为当前时间后 120 分钟(2 小时);notBefore 传 null,令牌立即生效。这与验签配置中的 ValidateLifetime = true 配合:2 小时后令牌过期,服务端将拒绝访问。
  4. 签发/受众对齐:issuer 与 audience 必须分别等于验签端的 ValidIssuer 与 ValidAudience,这是 ValidateIssuer/ValidateAudience 通过的前提——任何一处不一致都会导致 401。

最后通过 JwtSecurityTokenHandler().WriteToken(token) 将 JwtSecurityToken 序列化为标准的 Base64Url 三段式 JWT 字符串,由 /jwt 端点以 JSON 形式返回:

app.MapGet("/jwt", () => Results.Json(new { token = GenerateJSONWebToken()}));

受保护端点与前端调用闭环

示例在 Program.cs 中定义了一个需要认证才能访问的接口:

app.MapGet("/secret", (ClaimsPrincipal user) => $"Hello {user.Identity?.Name}. This is a secret!")
    .RequireAuthorization();
  • 通过方法参数注入 ClaimsPrincipal user,直接读取认证成功后的用户身份;
  • .RequireAuthorization() 是授权门槛:未携带合法令牌的请求会被拒之门外(返回 401),这正是 DefaultChallengeScheme = "Bearer" 发挥作用的地方。

为了让读者直观看到完整闭环,示例的 / 根路径返回了一段内嵌 JavaScript 的 HTML 页面(Program.cs),其交互流程就是最标准的 JWT 使用范式:

  1. 页面展示当前使用的认证方案名 JwtBearerDefaults.AuthenticationScheme(即 Bearer);
  2. 点击 “Get Secret” 按钮后,前端先 fetch('/jwt') 获取服务端签发的令牌;
  3. 再将令牌以 Authorization: Bearer <token> 请求头携带,fetch('/secret') 请求受保护接口;
  4. 页面最终展示服务端返回的 Hello Anne. This is a secret!。
const url2 = window.location.protocol + '//' + window.location.host  + "/secret";
const response2 = await fetch(url2,  {
    headers: { 'Accept': 'text/plain', 'Authorization': 'Bearer ' + json.token, }
});

这演示了 JWT 认证区别于 Cookie 认证的核心特征:令牌由客户端显式携带(通常是 Authorization 请求头),服务端无状态验签。完整请求链路为:GET /jwt 签发 → GET /secret 携带 Bearer 令牌 → 中间件按默认方案解析并验签 → 授权通过 → 端点读取 ClaimsPrincipal 返回用户信息。

运行与验证

在仓库根目录(SDK 版本需满足 global.json 的 10.0.0 要求)进入示例目录后运行:

cd projects/authentication/authentication-1
dotnet run

浏览器访问 https://localhost:5001/(或控制台输出的实际地址),即可看到页面上的 “Get Secret” 按钮,点击即可观察 签发 → 携带 → 校验 → 返回受保护内容 的完整认证流程。

延伸:从“显式配置”到“零配置”与多方案并存

builder.AddAuthentication().AddJwtBearer() 的“简化”特性在同仓库其他示例中有更极致的体现:

  • authentication-4(Program.cs)基于 Web API 模板,仅调用 builder.Services.AddAuthentication().AddJwtBearer(); 一行,完全省略手写 TokenValidationParameters,配合 .NET 10 内置 OpenAPI 与 dotnet user-jwts create 生成开发用令牌(见 authentication-4/Readme.md)。authentication-1 与它的区别在于:前者显式声明全部校验参数,更适合理解底层语义或对接企业级令牌签发方。
  • authentication-3(Program.cs)演示 AddCookie() 与 AddJwtBearer() 在同一应用中共存,通过 .RequireAuthorization(options => options.AddAuthenticationSchemes(...)) 按接口区分允许的认证方案。
  • authentication-2(Program.cs)是 Cookie 版本的对照样例,通过 context.SignInAsync / context.SignOutAsync 管理会话,与无状态的 JWT 形成鲜明对比。
  • authentication-5(Readme.md)则展示了从“手写 JWT”升级为 AddIdentityApiEndpoints<ApplicationUser>().AddEntityFrameworkStores<ApplicationDBContext>() 的完整 Identity 认证体系。

小结

通过 authentication-1 示例 可以看到,ASP.NET Core 的 JWT Bearer 认证只需围绕四条语句组织:AddAuthorization() 注册授权、AddAuthentication(options => ...) 指定默认方案、.AddJwtBearer(options => ...) 配置校验规则、UseAuthorization() 挂载中间件。核心要诀在于签发端与验签端的密钥、签发方、受众三者必须完全对齐,再配合 .RequireAuthorization() 与 ClaimsPrincipal 参数注入,即可在最小 API 中落地一套完整、可运行、可扩展的令牌认证方案。

登录后查看全文
practical-aspnetcore