🔐auth0-aspnetcore-api
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: JWT Bearerトークンの検証、スコープチェック、またはDoPPバインディングによってASP.NET Core Web APIのエンドポイントを保護する場合。 フロントエンドやモバイルアプリからアクセストークンを受け取るステートレスなREST APIに向けて、`Auth0.AspNetCore.Authentication.Api` を統合します。
原文を表示
Use when protecting ASP.NET Core Web API endpoints with JWT Bearer token validation, scope checks, or DPoP binding. Integrates Auth0.AspNetCore.Authentication.Api for stateless REST APIs receiving access tokens from frontends or mobile apps.
ユースケース
- ✓JWT Bearerトークンを検証するとき
- ✓スコープをチェックするとき
- ✓DoPPバインディングを行うとき
- ✓REST APIのエンドポイント保護
本文(日本語訳)
Auth0 ASP.NET Core Web API 連携
Auth0.AspNetCore.Authentication.Api を使用して、JWT アクセストークン検証で ASP.NET Core Web API のエンドポイントを保護します。
前提条件
- .NET 8.0 SDK 以上
- Auth0 API が設定済みであること(Application ではなく、API リソースとして作成が必要)
- Auth0 をまだセットアップしていない場合は、先に
auth0-quickstartスキルを使用してください
使用しない場合
- サーバーレンダリングの Web アプリケーション — MVC / Razor Pages アプリにはセッションベース認証(
Auth0.AspNetCore.Authentication)を使用 - シングルページアプリケーション — クライアントサイド認証には
auth0-react、auth0-vue、auth0-angularを使用 - モバイルアプリケーション — React Native / Expo には
auth0-react-nativeを使用 - Blazor WebAssembly — 異なる認証アプローチが必要(OIDC クライアントサイド)
クイックスタート手順
1. SDK のインストール
dotnet add package Auth0.AspNetCore.Authentication.Api
2. Auth0 API の作成
Auth0 に API(Application ではなく)を作成する必要があります。
ここで一度停止し、ユーザーに確認してください。
他の操作を行う前に、以下の質問をそのまま尋ね、回答を待ってください:
「Auth0 API リソースの作成方法を選んでください:
- 自動 — Auth0 CLI スクリプトを実行してリソースを作成し、正確な値を appsettings.json に自動で書き込みます。
- 手動 — Auth0 Dashboard(または
auth0 apis create)で API を自分で作成し、Domain と Audience を教えてください。どちらを希望しますか?(1 = 自動 / 2 = 手動)」
ユーザーが回答するまで、いかなるセットアップ手順にも進まないでください。手動をデフォルトにしないでください。
自動を選んだ場合: 完全な CLI スクリプトは セットアップガイド を参照してください。自動の場合は appsettings.json が自動生成されるため、下記のステップ 3 をスキップしてステップ 4 に直接進んでください。
手動を選んだ場合: User Secrets や環境変数のオプションを含む詳細な手順は セットアップガイド(手動セットアップのセクション)を参照してください。その後、下記のステップ 3 に進んでください。
手動での API 作成のクイックリファレンス:
# Auth0 CLI を使用する場合
auth0 apis create \
--name "My ASP.NET Core API" \
--identifier https://my-api.example.com
または Auth0 Dashboard → Applications → APIs から手動で作成してください。
3. appsettings.json の設定
{
"Auth0": {
"Domain": "your-tenant.auth0.com",
"Audience": "https://my-api.example.com"
}
}
重要: Domain に https:// を含めないでください。ライブラリが Authority URL を自動的に構築します。
4. Program.cs の設定
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();
// ミドルウェアの順序が重要: 認証(Authentication)は認可(Authorization)より前に配置
app.UseAuthentication();
app.UseAuthorization();
// エンドポイントをここに追加(ステップ 5 参照)
app.MapGet("/api/public", () => Results.Ok(new { message = "Public" }));
app.Run();
5. エンドポイントの保護
Minimal API の場合:
// パブリックエンドポイント — 認証不要
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();
コントローラーベースの場合:
[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. 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 タブから取得してください。
よくある間違い
| 間違い | 修正方法 |
|---|---|
Domain に https:// が含まれている |
your-tenant.auth0.com の形式のみ使用(スキームプレフィックスは不要) |
| Audience が API Identifier と一致しない | Auth0 Dashboard で設定した API Identifier と完全に一致させること |
| Auth0 に API ではなく Application を作成した | Auth0 Dashboard → Applications → APIs で API リソースを作成すること |
| ミドルウェアの順序が間違っている | UseAuthentication() は UseAuthorization() より前に配置すること |
| アクセストークンの代わりに ID トークンを使用している | API 認証には ID トークンではなくアクセストークンを使用すること |
| ローカル環境で HTTPS 証明書エラーが発生する | dotnet dev-certs https --trust を実行すること |
スコープベースの認可
スコープポリシーの定義と適用については、インテグレーションガイド を参照してください。
DPoP サポート
RFC 9449 に準拠した Proof-of-Possession トークンバインディングをビルトインでサポートしています。設定方法については インテグレーションガイド を参照してください。
関連スキル
auth0-quickstart— Auth0 の基本セットアップauth0-mfa— 多要素認証(MFA)の追加auth0-cli— ターミナルから Auth0 リソースを管理
クイックリファレンス
設定オプション:
options.Domain— Auth0 テナントドメイン(https://プレフィックスなし)(必須)options.JwtBearerOptions.Audience— Auth0 API 設定の API Identifier(必須)options.JwtBearerOptions— Microsoft JWT Bearer オプションへの完全アクセス
ユーザークレーム:
ctx.User.FindFirst("sub")?.Value— ユーザー ID(サブジェクト)ctx.User.FindFirst("scope")?.Value— スペース区切りのスコープ一覧ctx.User.FindAll("scope")— すべてのスコープクレーム
主なユースケース:
- Minimal API ルートの保護 →
.RequireAuthorization()(ステップ 5 参照) - コントローラーアクションの保護 →
[Authorize]属性(ステップ 5 参照) - スコープの適用 → インテグレーションガイド
- DPoP トークンバインディング → インテグレーションガイド
- JWT Bearer の高度な設定 → API リファレンス
詳細ドキュメント
- セットアップガイド — Auth0 CLI セットアップ、環境設定
- インテグレーションガイド — スコープポリシー、DPoP、コントローラーパターン、エラーハンドリング
- API リファレンス — 完全な設定オプションと拡張メソッド
参考リンク
原文(English)を表示
Auth0 ASP.NET Core Web API Integration
Protect ASP.NET Core Web API endpoints with JWT access token validation using Auth0.AspNetCore.Authentication.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-quickstartskill first
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, orauth0-angularfor client-side auth - Mobile applications - Use
auth0-react-nativefor React Native/Expo - Blazor WebAssembly - Requires different auth approach (OIDC client-side)
Quick Start Workflow
1. Install SDK
dotnet add package Auth0.AspNetCore.Authentication.Api
2. Create 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
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:
# Using 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
3. Configure appsettings.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.
4. Configure 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();
5. Protect Endpoints
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();
Controller-based:
[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
Test public endpoint:
curl http://localhost:5000/api/public
Test protected endpoint (requires access token):
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.
Common Mistakes
| Mistake | Fix |
|---|---|
Domain includes https:// |
Use your-tenant.auth0.com format only - no scheme prefix |
| 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 | UseAuthentication() must come before UseAuthorization() |
| Using ID token instead of access token | Must use access token for API auth, not ID token |
| HTTPS certificate errors locally | Run dotnet dev-certs https --trust |
Scope-Based Authorization
See Integration Guide for defining and enforcing scope policies.
DPoP Support
Built-in proof-of-possession token binding per RFC 9449. See Integration Guide for configuration.
Related Skills
auth0-quickstart- Basic Auth0 setupauth0-mfa- Add Multi-Factor Authenticationauth0-cli- Manage Auth0 resources from the terminal
Quick Reference
Configuration Options:
options.Domain- Auth0 tenant domain, nohttps://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 scopesctx.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
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
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。