auth0-aspnetcore-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 ASP.NET Core Web API Integration
Auth0 ASP.NET Core Web API 集成方案
Protect ASP.NET Core Web API endpoints with JWT access token validation using Auth0.AspNetCore.Authentication.Api.
通过Auth0.AspNetCore.Authentication.Api实现JWT访问令牌验证,保护ASP.NET Core Web API端点。
Prerequisites
前置要求
- .NET 8.0 SDK or higher
- Auth0 API configured (not Application - must be API resource)
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- .NET 8.0 SDK 或更高版本
- 已配置Auth0 API(必须是API资源,而非应用程序)
- 如果你还没有完成Auth0配置,请先使用skill
auth0-quickstart
When NOT to Use
不适用场景
- Server-rendered web applications - Use session-based auth (Auth0.AspNetCore.Authentication) for MVC/Razor Pages apps
- Single Page Applications - Use ,
auth0-react, orauth0-vuefor client-side authauth0-angular - Mobile applications - Use for React Native/Expo
auth0-react-native - Blazor WebAssembly - Requires different auth approach (OIDC client-side)
- 服务端渲染Web应用:MVC/Razor Pages应用请使用基于会话的认证(Auth0.AspNetCore.Authentication)
- 单页应用:客户端认证请使用、
auth0-react或auth0-vueauth0-angular - 移动应用:React Native/Expo应用请使用
auth0-react-native - Blazor WebAssembly:需要采用不同的认证方案(客户端OIDC)
Quick Start Workflow
快速入门流程
1. Install SDK
1. 安装SDK
bash
dotnet add package Auth0.AspNetCore.Authentication.Apibash
dotnet add package Auth0.AspNetCore.Authentication.Api2. Create Auth0 API
2. 创建Auth0 API
You need an API (not Application) in Auth0.
STOP — ask the user before proceeding.Ask exactly this question and wait for their answer before doing anything else:"How would you like to create the Auth0 API resource?
- Automated — I'll run Auth0 CLI scripts that create the resource and write the exact values to your appsettings.json automatically.
- Manual — You create the API yourself in the Auth0 Dashboard (or via
) and provide me the Domain and Audience.auth0 apis createWhich do you prefer? (1 = Automated / 2 = Manual)"Do NOT proceed to any setup steps until the user has answered. Do NOT default to manual.
If the user chose Automated, follow the Setup Guide for complete CLI scripts. The automated path writes for you — skip Step 3 below and proceed directly to Step 4.
appsettings.jsonIf the user chose Manual, follow the Setup Guide (Manual Setup section) for full instructions including User Secrets and environment variable options. Then continue with Step 3 below.
Quick reference for manual API creation:
bash
undefined你需要在Auth0中创建一个API(而非应用程序)。
注意 — 继续操作前请先询问用户。请严格按照以下内容提问,待用户答复后再进行后续操作:"你希望如何创建Auth0 API资源?
- 自动创建 — 我将运行Auth0 CLI脚本创建资源,并自动将对应配置值写入你的appsettings.json文件。
- 手动创建 — 你自行在Auth0控制台创建API(或通过
命令创建),并向我提供Domain和Audience参数。auth0 apis create你更倾向哪种方式?(1 = 自动 / 2 = 手动)"用户未答复前请勿进行任何配置步骤,也不要默认选择手动方式。
如果用户选择自动创建:请参照配置指南获取完整CLI脚本,自动流程会为你生成配置,可跳过下方第3步直接进入第4步。
appsettings.json如果用户选择手动创建:请参照配置指南(手动配置章节)获取完整说明,包括用户机密和环境变量配置选项,完成后继续执行下方第3步。
手动创建API的快速参考命令:
bash
undefinedUsing Auth0 CLI
使用Auth0 CLI创建
Or create manually in Auth0 Dashboard → Applications → APIs
也可以在Auth0控制台 → 应用 → APIs中手动创建。3. Configure appsettings.json
3. 配置appsettings.json
json
{
"Auth0": {
"Domain": "your-tenant.auth0.com",
"Audience": "https://my-api.example.com"
}
}Important: Domain must NOT include . The library constructs the authority URL automatically.
https://json
{
"Auth0": {
"Domain": "your-tenant.auth0.com",
"Audience": "https://my-api.example.com"
}
}重要提示:Domain不要包含前缀,类库会自动构建授权地址。
https://4. Configure Program.cs
4. 配置Program.cs
csharp
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();csharp
var builder = WebApplication.CreateBuilder(args);
// 注册Auth0 JWT验证服务
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();
// 中间件顺序很重要:认证中间件必须在授权中间件之前
app.UseAuthentication();
app.UseAuthorization();
// 在此处添加你的端点(参考第5步)
app.MapGet("/api/public", () => Results.Ok(new { message = "Public" }));
app.Run();5. Protect Endpoints
5. 保护端点
Minimal API:
csharp
// 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();Controller-based:
csharp
[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 });
}Minimal API模式:
csharp
// 公开端点 - 无需认证
app.MapGet("/api/public", () => Results.Ok(new { message = "Hello from a public endpoint!" }));
// 受保护端点 - 需要有效的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();控制器模式:
csharp
[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 });
}6. Test API
6. 测试API
Test public endpoint:
bash
curl http://localhost:5000/api/publicTest protected endpoint (requires access token):
bash
curl http://localhost:5000/api/private \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"Get a test token via Client Credentials flow or Auth0 Dashboard → APIs → Test tab.
测试公开端点:
bash
curl http://localhost:5000/api/public测试受保护端点(需要访问令牌):
bash
curl http://localhost:5000/api/private \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"可通过客户端凭证流或者Auth0控制台 → APIs → 测试标签页获取测试令牌。
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
Domain includes | Use |
| Audience doesn't match API Identifier | Must exactly match the API Identifier set in Auth0 Dashboard |
| Created Application instead of API in Auth0 | Must create API resource in Auth0 Dashboard → Applications → APIs |
| Wrong middleware order | |
| Using ID token instead of access token | Must use access token for API auth, not ID token |
| HTTPS certificate errors locally | Run |
| 错误 | 修复方案 |
|---|---|
Domain包含 | 仅使用 |
| Audience与API标识符不匹配 | 必须与Auth0控制台中设置的API标识符完全一致 |
| 在Auth0中创建了应用而非API | 必须在Auth0控制台 → 应用 → APIs中创建API资源 |
| 中间件顺序错误 | |
| 使用ID令牌而非访问令牌 | API认证必须使用访问令牌,不能使用ID令牌 |
| 本地HTTPS证书错误 | 执行 |
Scope-Based Authorization
基于作用域的授权
See Integration Guide for defining and enforcing scope policies.
查看集成指南了解如何定义和执行作用域策略。
DPoP Support
DPoP支持
Built-in proof-of-possession token binding per RFC 9449. See Integration Guide for configuration.
内置符合RFC 9449标准的持有证明令牌绑定能力,查看集成指南了解配置方式。
Related Skills
相关Skill
- - Basic Auth0 setup
auth0-quickstart - - Add Multi-Factor Authentication
auth0-mfa
- - Auth0基础配置
auth0-quickstart - - 添加多因素认证能力
auth0-mfa
Quick Reference
快速参考
Configuration Options:
- - Auth0 tenant domain, no
options.Domainprefix (required)https:// - - API Identifier from Auth0 API settings (required)
options.JwtBearerOptions.Audience - - Full access to underlying Microsoft JWT Bearer options
options.JwtBearerOptions
User Claims:
- - User ID (subject)
ctx.User.FindFirst("sub")?.Value - - Space-separated scopes
ctx.User.FindFirst("scope")?.Value - - All scope claims
ctx.User.FindAll("scope")
Common Use Cases:
- Protect Minimal API routes → (see Step 5)
.RequireAuthorization() - Protect controller actions → attribute (see Step 5)
[Authorize] - Scope enforcement → Integration Guide
- DPoP token binding → Integration Guide
- Advanced JWT Bearer config → API Reference
配置选项:
- - Auth0租户域名,不带
options.Domain前缀(必填)https:// - - Auth0 API设置中的API标识符(必填)
options.JwtBearerOptions.Audience - - 可完全访问微软原生JWT Bearer配置项
options.JwtBearerOptions
用户声明:
- - 用户ID(subject)
ctx.User.FindFirst("sub")?.Value - - 空格分隔的作用域列表
ctx.User.FindFirst("scope")?.Value - - 所有作用域声明
ctx.User.FindAll("scope")
常见使用场景:
- 保护Minimal API路由 → (参考第5步)
.RequireAuthorization() - 保护控制器方法 → 特性(参考第5步)
[Authorize] - 作用域校验 → 集成指南
- DPoP令牌绑定 → 集成指南
- 高级JWT Bearer配置 → API参考
Detailed Documentation
详细文档
- Setup Guide - Auth0 CLI setup, environment configuration
- Integration Guide - Scope policies, DPoP, controller patterns, error handling
- API Reference - Complete configuration options and extension methods
- 配置指南 - Auth0 CLI配置、环境变量配置
- 集成指南 - 作用域策略、DPoP、控制器模式、错误处理
- API参考 - 完整配置选项和扩展方法