auth0-aspnetcore-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 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
    auth0-quickstart
    skill first
  • .NET 8.0 SDK 或更高版本
  • 已配置Auth0 API(必须是API资源,而非应用程序)
  • 如果你还没有完成Auth0配置,请先使用
    auth0-quickstart
    skill

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
    ,
    auth0-vue
    , or
    auth0-angular
    for client-side auth
  • Mobile applications - Use
    auth0-react-native
    for React Native/Expo
  • Blazor WebAssembly - Requires different auth approach (OIDC client-side)

  • 服务端渲染Web应用:MVC/Razor Pages应用请使用基于会话的认证(Auth0.AspNetCore.Authentication)
  • 单页应用:客户端认证请使用
    auth0-react
    auth0-vue
    auth0-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.Api
bash
dotnet add package Auth0.AspNetCore.Authentication.Api

2. 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?
  1. Automated — I'll run Auth0 CLI scripts that create the resource and write the exact values to your appsettings.json automatically.
  2. Manual — You create the API yourself in the Auth0 Dashboard (or via
    auth0 apis create
    ) and provide me the Domain and Audience.
Which 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
appsettings.json
for you — skip Step 3 below and proceed directly to Step 4.
If 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资源?
  1. 自动创建 — 我将运行Auth0 CLI脚本创建资源,并自动将对应配置值写入你的appsettings.json文件。
  2. 手动创建 — 你自行在Auth0控制台创建API(或通过
    auth0 apis create
    命令创建),并向我提供Domain和Audience参数。
你更倾向哪种方式?(1 = 自动 / 2 = 手动)"
用户未答复前请勿进行任何配置步骤,也不要默认选择手动方式。
如果用户选择自动创建:请参照配置指南获取完整CLI脚本,自动流程会为你生成
appsettings.json
配置,可跳过下方第3步直接进入第4步。
如果用户选择手动创建:请参照配置指南(手动配置章节)获取完整说明,包括用户机密和环境变量配置选项,完成后继续执行下方第3步。
手动创建API的快速参考命令:
bash
undefined

Using Auth0 CLI

使用Auth0 CLI创建

auth0 apis create
--name "My ASP.NET Core API"
--identifier https://my-api.example.com

Or create manually in Auth0 Dashboard → Applications → APIs
auth0 apis create
--name "My ASP.NET Core API"
--identifier https://my-api.example.com

也可以在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
https://
. The library constructs the authority URL automatically.
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/public
Test 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

常见错误

MistakeFix
Domain includes
https://
Use
your-tenant.auth0.com
format only - no scheme prefix
Audience doesn't match API IdentifierMust exactly match the API Identifier set in Auth0 Dashboard
Created Application instead of API in Auth0Must create API resource in Auth0 Dashboard → Applications → APIs
Wrong middleware order
UseAuthentication()
must come before
UseAuthorization()
Using ID token instead of access tokenMust use access token for API auth, not ID token
HTTPS certificate errors locallyRun
dotnet dev-certs https --trust

错误修复方案
Domain包含
https://
前缀
仅使用
your-tenant.auth0.com
格式,不要添加协议前缀
Audience与API标识符不匹配必须与Auth0控制台中设置的API标识符完全一致
在Auth0中创建了应用而非API必须在Auth0控制台 → 应用 → APIs中创建API资源
中间件顺序错误
UseAuthentication()
必须放在
UseAuthorization()
之前
使用ID令牌而非访问令牌API认证必须使用访问令牌,不能使用ID令牌
本地HTTPS证书错误执行
dotnet dev-certs https --trust
命令

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

  • auth0-quickstart
    - Basic Auth0 setup
  • auth0-mfa
    - Add Multi-Factor Authentication

  • auth0-quickstart
    - Auth0基础配置
  • auth0-mfa
    - 添加多因素认证能力

Quick Reference

快速参考

Configuration Options:
  • options.Domain
    - Auth0 tenant domain, no
    https://
    prefix (required)
  • options.JwtBearerOptions.Audience
    - API Identifier from Auth0 API settings (required)
  • options.JwtBearerOptions
    - Full access to underlying Microsoft JWT Bearer options
User Claims:
  • ctx.User.FindFirst("sub")?.Value
    - User ID (subject)
  • ctx.User.FindFirst("scope")?.Value
    - Space-separated scopes
  • ctx.User.FindAll("scope")
    - All scope claims
Common Use Cases:
  • Protect Minimal API routes →
    .RequireAuthorization()
    (see Step 5)
  • Protect controller actions →
    [Authorize]
    attribute (see Step 5)
  • Scope enforcement → Integration Guide
  • DPoP token binding → Integration Guide
  • Advanced JWT Bearer config → API Reference

配置选项:
  • options.Domain
    - Auth0租户域名,不带
    https://
    前缀(必填)
  • options.JwtBearerOptions.Audience
    - Auth0 API设置中的API标识符(必填)
  • options.JwtBearerOptions
    - 可完全访问微软原生JWT Bearer配置项
用户声明:
  • ctx.User.FindFirst("sub")?.Value
    - 用户ID(subject)
  • ctx.User.FindFirst("scope")?.Value
    - 空格分隔的作用域列表
  • ctx.User.FindAll("scope")
    - 所有作用域声明
常见使用场景:
  • 保护Minimal API路由 →
    .RequireAuthorization()
    (参考第5步)
  • 保护控制器方法 →
    [Authorize]
    特性(参考第5步)
  • 作用域校验 → 集成指南
  • 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参考 - 完整配置选项和扩展方法

References

参考资料