用途
本技能用于保护 ASP.NET Core Web API 端点,基于 Auth0.AspNetCore.Authentication.Api 实现 JWT 访问令牌验证、scope 权限检查以及 DPoP 令牌绑定。适用于需要为 .NET 8.0 SDK 或更高版本的 Web API 添加认证与授权的开发场景。
主要能力
- 使用 Auth0.AspNetCore.Authentication.Api 注册 JWT 验证。
- 支持 JWT Bearer 令牌验证,可配置 Domain 与 Audience。
- 支持基于 scope 的授权策略。
- 内置符合 RFC 9449 的 DPoP 持有证明令牌绑定支持。
- 提供 Minimal API 与基于控制器两种端点保护方式。
- 可访问底层 Microsoft JWT Bearer 选项进行高级配置。
使用方式
前置条件
- .NET 8.0 SDK 或更高版本。
- 已在 Auth0 中配置 API(必须是 API 资源,而非 Application)。
- 若尚未设置 Auth0,可先使用 auth0-quickstart 技能。
快速开始工作流
- 安装 SDK:
dotnet add package Auth0.AspNetCore.Authentication.Api
- 创建 Auth0 API。需要在 Auth0 中创建 API(不是 Application)。技能要求先询问用户选择自动化或手动方式创建 API 资源,在用户回答前不得继续任何设置步骤,也不得默认使用手动方式。
手动创建 API 的 CLI 参考:
auth0 apis create \
--name "My ASP.NET Core API" \
--identifier https://my-api.example.com
或在 Auth0 Dashboard → Applications → APIs 中手动创建。
- 配置 appsettings.json:
{
"Auth0": {
"Domain": "your-tenant.auth0.com",
"Audience": "https://my-api.example.com"
}
}
注意:Domain 不得包含 https://,库会自动构建 authority URL。
- 配置 Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Register Auth0 JWT validation
builder.Services.AddAuth0ApiAuthentication(options =>
{
options.Domain = builder.Configuration["Auth0:Domain"];
options.JwtBearerOptions = new JwtBearerOptions
{
Audience = builder.Configuration["Auth0:Audience"]
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
// Middleware order matters: authentication before authorization
app.UseAuthentication();
app.UseAuthorization();
// Add your endpoints here (see Step 5)
app.MapGet("/api/public", () => Results.Ok(new { message = "Public" }));
app.Run();
- 保护端点。
Minimal API 示例:
// Public endpoint - no authentication
app.MapGet("/api/public", () => Results.Ok(new { message = "Hello from a public endpoint!" }));
// Protected endpoint - requires valid JWT
app.MapGet("/api/private", (HttpContext ctx) =>
{
var userId = ctx.User.FindFirst("sub")?.Value;
return Results.Ok(new { message = "Hello from a protected endpoint!", userId });
}).RequireAuthorization();
基于控制器的示例:
[ApiController]
[Route("api")]
public class MessagesController : ControllerBase
{
[HttpGet("public")]
public IActionResult Public() =>
Ok(new { message = "Hello from a public endpoint!" });
[Authorize]
[HttpGet("private")]
public IActionResult Private() =>
Ok(new { message = "Hello from a protected endpoint!", userId = User.FindFirst("sub")?.Value });
}
- 测试 API。
测试公开端点:
curl http://localhost:5000/api/public
测试受保护端点(需要访问令牌):
curl http://localhost:5000/api/private \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
可通过 Client Credentials 流程或 Auth0 Dashboard → APIs → Test 标签页获取测试令牌。
适用场景
- 为 ASP.NET Core Web API 添加 JWT 访问令牌验证。
- 对 API 端点实施 scope 权限检查。
- 需要 DPoP 令牌绑定的 API 安全场景。
- 使用 Minimal API 或控制器方式保护端点。
限制
以下场景不适用本技能:
- 服务端渲染 Web 应用:应使用基于会话的认证(Auth0.AspNetCore.Authentication)用于 MVC/Razor Pages 应用。
- 单页应用:应使用 auth0-react、auth0-vue 或 auth0-angular 进行客户端认证。
- 移动应用:应使用 auth0-react-native 用于 React Native/Expo。
- Blazor WebAssembly:需要不同的认证方式(客户端 OIDC)。
常见错误与修复
- Domain 包含 https://:仅使用 your-tenant.auth0.com 格式,不带协议前缀。
- Audience 与 API Identifier 不匹配:必须与 Auth0 Dashboard 中设置的 API Identifier 完全一致。
- 在 Auth0 中创建了 Application 而非 API:必须在 Auth0 Dashboard → Applications → APIs 中创建 API 资源。
- 中间件顺序错误:UseAuthentication() 必须在 UseAuthorization() 之前。
- 使用 ID token 而非 access token:API 认证必须使用 access token,而非 ID token。
- 本地 HTTPS 证书错误:运行 dotnet dev-certs https --trust。
配置选项与用户声明
配置选项:
- options.Domain:Auth0 租户域名,不带 https:// 前缀(必填)。
- options.JwtBearerOptions.Audience:来自 Auth0 API 设置的 API Identifier(必填)。
- options.JwtBearerOptions:可完全访问底层 Microsoft JWT Bearer 选项。
用户声明:
- ctx.User.FindFirst("sub")?.Value:用户 ID(subject)。
- ctx.User.FindFirst("scope")?.Value:以空格分隔的 scope。
- ctx.User.FindAll("scope"):所有 scope 声明。
相关技能
- auth0-quickstart:基础 Auth0 设置。
- auth0-mfa:添加多因素认证。
- auth0-cli:从终端管理 Auth0 资源。
详细文档
- Setup Guide:Auth0 CLI 设置、环境配置。
- Integration Guide:scope 策略、DPoP、控制器模式、错误处理。
- API Reference:完整配置选项与扩展方法。
参考
- Auth0 ASP.NET Core Web API Quickstart
- SDK GitHub Repository
- API Documentation
- Access Tokens Guide