claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialsecurity

🔐auth0-fastapi-api

プラグイン
auth0
ライセンス
Apache-2.0

説明

次のような場合に使用: FastAPI エンドポイントを JWT Bearer トークン検証、スコープチェック、または DPoP バインディングで保護する場合。 アクセストークンを受け取るステートレス API に対して `auth0-fastapi-api` を統合します — ユーザーが「FastAPI エンドポイントを保護したい」や「FastAPI でトークンを検証したい」と述べた場合にも使用してください。

原文を表示

Use when protecting FastAPI endpoints with JWT Bearer token validation, scope checks, or DPoP binding. Integrates auth0-fastapi-api for stateless APIs receiving access tokens — use even if the user says "secure my FastAPI endpoints" or "validate tokens in FastAPI".

ユースケース

  • FastAPIエンドポイントをJWT検証で保護する
  • スコープチェックでアクセス制御したい
  • DPoPバインディングで保護したい
  • ステートレスAPIでトークン検証する

本文(日本語訳)

Auth0 FastAPI API インテグレーション

auth0-fastapi-api を使用して、JWT アクセストークンの検証により FastAPI API エンドポイントを保護します。

注意: この SDK は現在ベータ版です。安定版 1.0 リリース前に API インターフェースが変更される可能性があります。最新バージョンは PyPI を確認してください。Python >= 3.9 および FastAPI >= 0.115.11 が必要です。


前提条件

  • FastAPI アプリケーション(Python 3.9 以上)
  • Auth0 API リソースの設定済み(Application ではなく、必ず API であること)
  • Auth0 がまだセットアップされていない場合は、先に auth0-quickstart スキルを使用してください

使用すべきでないケース

  • サーバーサイドレンダリングの Web アプリケーション — 代わりにセッションベースのログイン/ログアウトフローを使用してください
  • シングルページアプリケーション — クライアントサイドの認証には auth0-reactauth0-vue、または auth0-angular を使用してください
  • モバイルアプリケーションauth0-react-native または auth0-android を使用してください
  • トークンの発行 — このスキルはアクセストークンの検証用であり、発行用ではありません

クイックスタート手順

1. SDK のインストール

pip install auth0-fastapi-api python-dotenv

2. Auth0 API の作成

Auth0 に API(Application ではない)を作成する必要があります。

ここで一度停止し、ユーザーに確認してから先に進んでください。

以下の質問をそのまま行い、回答を受け取るまで一切の作業を進めないでください:

「Auth0 API リソースはどのように作成しますか?

  1. 自動 — Auth0 CLI スクリプトを実行して、リソースの作成と .env への設定値の書き込みを自動で行います。
  2. 手動 — Auth0 ダッシュボード(または auth0 apis create)で API を自分で作成し、Domain と Audience を教えてください。

どちらをご希望ですか?(1 = 自動 / 2 = 手動)」

ユーザーが回答するまで、セットアップ手順には一切進まないでください。手動をデフォルトにしないでください。

自動を選んだ場合、完全な CLI スクリプトについては セットアップガイド を参照してください。自動の場合は .env が自動で書き込まれます — 下記のステップ 3 をスキップし、ステップ 4 に進んでください。

手動を選んだ場合、詳細な手順については セットアップガイド(手動セットアップのセクション)を参照してください。その後、下記のステップ 3 に進んでください。

手動で API を作成する際のクイックリファレンス:

# Auth0 CLI を使用する場合
auth0 apis create \
  --name "My FastAPI API" \
  --identifier https://my-api.example.com

または Auth0 ダッシュボード → Applications → APIs から手動で作成することもできます。

3. 環境設定

.env ファイルを作成します:

AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com

AUTH0_DOMAIN は Auth0 テナントのドメインです(https:// は含めません)。 AUTH0_AUDIENCE は Auth0 で API リソースを作成する際に設定した API の識別子です。

4. Auth0 の初期化

import os
from fastapi import FastAPI, Depends
from fastapi_plugin import Auth0FastAPI
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),
    audience=os.getenv("AUTH0_AUDIENCE"),
)

Auth0FastAPI のインスタンスはアプリケーションごとに 1 つ作成し、ルート全体で再利用してください。 Domain や Audience をソースコードにハードコードせず、必ず環境変数から読み込んでください。

5. ルートの保護

# 有効なアクセストークンを必須とする
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
    return {"user": claims["sub"]}

# 認証不要
@app.get("/api/public")
async def public():
    return {"message": "Public endpoint"}

require_auth() 依存関係は Bearer トークンを検証し、issuer と audience を確認したうえで、デコードされた JWT クレームを返します。

エラーレスポンス:

  • 400 invalid_request — Authorization ヘッダーが存在しない、または不正な形式
  • 401 invalid_token — トークンの期限切れ、無効な署名、issuer/audience の不一致
  • 403 insufficient_scope — 有効なトークンだが必要なスコープが不足
  • 500 internal_server_error — 予期しないエラー

レスポンスボディの形式: {"detail": {"error": "...", "error_description": "..."}}

6. スコープチェックによるルートの保護

# read:messages スコープが必要
@app.get("/api/messages")
async def get_messages(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
    return {"messages": []}

# read:data と write:data の両スコープが必要
@app.post("/api/data")
async def write_data(claims: dict = Depends(auth0.require_auth(scopes=["read:data", "write:data"]))):
    return {"created": True}

require_auth(scopes=...) は JWT の scope クレームを確認します。 指定したすべてのスコープが存在する必要があります(AND 条件)。 スコープが不足している場合は 403 を返します。

7. トークンクレームへのアクセス

デコードされた JWT クレームは依存関係から直接返されます:

@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
    return {
        "sub": claims["sub"],          # ユーザー ID
        "scope": claims.get("scope"),  # 付与されたスコープ
    }

主なクレーム:

  • claims["sub"] — ユーザー/クライアント ID
  • claims["scope"] — スペース区切りで付与されたスコープ
  • claims["iss"] — issuer(Auth0 ドメインの URL)
  • claims["aud"] — audience
  • claims["exp"] — 有効期限のタイムスタンプ
  • claims["iat"] — 発行日時のタイムスタンプ

8. クレームを必要としないルートの保護

@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
    return {"message": "You need a valid access token to see this."}

9. API のテスト

# トークンなし — 401 が返ることを確認
curl http://localhost:8000/api/private

# 有効なアクセストークンを使用
curl http://localhost:8000/api/private \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

テスト用トークンは、Client Credentials フローまたは Auth0 ダッシュボード → APIs → Test タブから取得できます。


よくある間違い

間違い 対処法
domainaudience をソースにハードコードする 必ず環境変数から読み込む — 認証情報をコードに埋め込まない
python-josePyJWT を直接使用する 不要。auth0-fastapi-api が JWKS を通じてすべての検証を処理する
Authorization ヘッダーを手動でパースする SDK がトークンの抽出と検証を自動で行う
jwt.decode() を手動で呼び出す SDK が JWKS エンドポイントに対してトークンを検証する — 自分で検証しない
Auth0 JWT 検証に fastapi-users を使用する そのパッケージはユーザー管理用であり、Auth0 JWT 検証用ではない
Auth0 で API の代わりに Application を作成する API リソースを作成する必要がある(Applications → APIs)— Application は適切な audience を持つアクセストークンを発行しない
domainhttps:// 付きの完全な URL で渡す domain はベアドメイン(例: my-tenant.us.auth0.com)を指定する。https://my-tenant.us.auth0.com は不可
アクセストークンの代わりに ID トークンを使用する API 認証にはアクセストークンを使用する — ID トークンはクライアントアプリ用であり、API 認可用ではない
SPA クライアント向けの CORS を設定しない フロントエンドのオリジンからのリクエストを許可するために CORSMiddleware を追加する
os.getenv()None を返しても気づかない python-dotenv がインストールされていること、および Auth0FastAPI() の初期化前に load_dotenv() が呼ばれていることを確認する — または即座に失敗させるために os.environ[] を使用する

DPoP サポート

RFC 9449 に基づく Proof-of-Possession トークンバインディングをビルトインでサポートしています。 DPoP はデフォルトでミックスモード(Bearer トークンと DPoP トークンの両方を受け付ける)で有効になっています。 設定方法については インテグレーションガイド を参照してください。


関連スキル

  • auth0-quickstart — Auth0 の基本セットアップとフレームワーク検出
  • auth0-mfa — 多要素認証(MFA)の追加
  • auth0-cli — ターミナルから Auth0 リソースを管理

クイックリファレンス

Auth0FastAPI の設定:

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),       # 必須(または domains を使用)
    audience=os.getenv("AUTH0_AUDIENCE"),    # 必須
    dpop_enabled=True,                       # デフォルト。Bearer のみにする場合は False を設定
    dpop_required=False,                     # デフォルト。Bearer トークンを拒否する場合は True を設定
)

ルートの保護:

Depends(auth0.require_auth())                    # 有効なトークンであれば可
Depends(auth0.require_auth(scopes="read:res"))   # 単一スコープ
Depends(auth0.require_auth(scopes=["r", "w"]))   # すべてのスコープが必要

クレームへのアクセス:

claims["sub"]           # ユーザー/クライアント ID
claims["scope"]         # スペース区切りのスコープ

環境変数:

  • AUTH0_DOMAIN — Auth0 テナントのドメイン(例: tenant.us.auth0.com
  • AUTH0_AUDIENCE — API の識別子(例: https://api.example.com

主なユースケース:


詳細ドキュメント


参考リンク

原文(English)を表示

Auth0 FastAPI API Integration

Protect FastAPI API endpoints with JWT access token validation using auth0-fastapi-api.

Note: This SDK is currently in beta. The API surface may change before the stable 1.0 release. Check PyPI for the latest version. Requires Python >= 3.9 and FastAPI >= 0.115.11.


Prerequisites

  • FastAPI application (Python 3.9+)
  • Auth0 API resource configured (not an Application — must be an API)
  • If you don't have Auth0 set up yet, use the auth0-quickstart skill first

When NOT to Use

  • Server-rendered web applications — Use a session-based login/logout flow instead
  • Single Page Applications — Use auth0-react, auth0-vue, or auth0-angular for client-side auth
  • Mobile applications — Use auth0-react-native or auth0-android
  • Issuing tokens — This skill is for validating access tokens, not issuing them

Quick Start Workflow

1. Install SDK

pip install auth0-fastapi-api python-dotenv

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?

  1. Automated — I'll run Auth0 CLI scripts that create the resource and write the exact values to your .env 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 .env 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. Then continue with Step 3 below.

Quick reference for manual API creation:

# Using Auth0 CLI
auth0 apis create \
  --name "My FastAPI API" \
  --identifier https://my-api.example.com

Or create manually in Auth0 Dashboard → Applications → APIs

3. Configure Environment

Create .env:

AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com

AUTH0_DOMAIN is your Auth0 tenant domain (without https://). AUTH0_AUDIENCE is the API identifier you set when creating the API resource in Auth0.

4. Initialize Auth0

import os
from fastapi import FastAPI, Depends
from fastapi_plugin import Auth0FastAPI
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),
    audience=os.getenv("AUTH0_AUDIENCE"),
)

Create one Auth0FastAPI instance per application and reuse it across routes. Never hardcode the domain or audience — always use environment variables.

5. Protect Routes

# Require any valid access token
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
    return {"user": claims["sub"]}

# No authentication required
@app.get("/api/public")
async def public():
    return {"message": "Public endpoint"}

The require_auth() dependency validates the Bearer token, verifies the issuer and audience, and returns the decoded JWT claims.

Error responses:

  • 400 invalid_request — Missing or malformed Authorization header
  • 401 invalid_token — Expired token, invalid signature, wrong issuer/audience
  • 403 insufficient_scope — Valid token but missing required scopes
  • 500 internal_server_error — Unexpected errors

Response body format: {"detail": {"error": "...", "error_description": "..."}}

6. Protect Routes with Scope Checks

# Requires the read:messages scope
@app.get("/api/messages")
async def get_messages(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
    return {"messages": []}

# Requires both read:data and write:data scopes
@app.post("/api/data")
async def write_data(claims: dict = Depends(auth0.require_auth(scopes=["read:data", "write:data"]))):
    return {"created": True}

require_auth(scopes=...) checks the scope claim in the JWT. All specified scopes must be present (AND logic). Missing scopes return 403.

7. Access Token Claims

The decoded JWT claims are returned directly from the dependency:

@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
    return {
        "sub": claims["sub"],       # user ID
        "scope": claims.get("scope"),  # granted scopes
    }

Key claims:

  • claims["sub"] — user/client ID
  • claims["scope"] — space-separated granted scopes
  • claims["iss"] — issuer (your Auth0 domain URL)
  • claims["aud"] — audience
  • claims["exp"] — expiration timestamp
  • claims["iat"] — issued-at timestamp

8. Protect Routes Without Needing Claims

@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
    return {"message": "You need a valid access token to see this."}

9. Test the API

# No token — expect 401
curl http://localhost:8000/api/private

# With a valid access token
curl http://localhost:8000/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
Hardcoding domain or audience in source Always read from environment variables — never embed credentials in code
Using python-jose or PyJWT directly Not needed; auth0-fastapi-api handles all validation via JWKS
Manually parsing Authorization header The SDK extracts and validates the token automatically
Calling jwt.decode() manually The SDK verifies tokens against the JWKS endpoint — do not verify yourself
Using fastapi-users for Auth0 JWT validation That package is for user management, not Auth0 JWT verification
Created an Application instead of an API in Auth0 Must create an API resource (Applications → APIs) — an Application doesn't issue access tokens with the right audience
Passing domain as full URL with https:// domain should be the bare domain, e.g. my-tenant.us.auth0.com, not https://my-tenant.us.auth0.com
Using an ID token instead of an access token Must use the access token for API auth — ID tokens are for the client app, not for API authorization
Not configuring CORS for SPA clients Add CORSMiddleware to allow requests from your frontend origin
os.getenv() returns None silently Ensure python-dotenv is installed and load_dotenv() is called before Auth0FastAPI() initialization — or use os.environ[] to fail fast

DPoP Support

Built-in proof-of-possession token binding per RFC 9449. DPoP is enabled by default in mixed mode (accepts both Bearer and DPoP tokens). See Integration Guide for configuration.


Related Skills

  • auth0-quickstart - Basic Auth0 setup and framework detection
  • auth0-mfa - Add Multi-Factor Authentication
  • auth0-cli - Manage Auth0 resources from the terminal

Quick Reference

Auth0FastAPI configuration:

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),       # required (or use domains)
    audience=os.getenv("AUTH0_AUDIENCE"),    # required
    dpop_enabled=True,                       # default; set False for Bearer-only
    dpop_required=False,                     # default; set True to reject Bearer tokens
)

Route protection:

Depends(auth0.require_auth())                    # any valid token
Depends(auth0.require_auth(scopes="read:res"))   # single scope
Depends(auth0.require_auth(scopes=["r", "w"]))   # all scopes required

Accessing claims:

claims["sub"]           # user/client ID
claims["scope"]         # space-separated scopes

Environment variables:

  • AUTH0_DOMAIN — your Auth0 tenant domain (e.g. tenant.us.auth0.com)
  • AUTH0_AUDIENCE — your API identifier (e.g. https://api.example.com)

Common Use Cases:

  • Protect routes → Depends(auth0.require_auth()) (see Step 5)
  • Scope enforcement → Depends(auth0.require_auth(scopes="...")) (see Step 6)
  • DPoP token binding → Integration Guide
  • Reverse proxy setup → Integration Guide
  • Advanced configuration → API Reference

Detailed Documentation

  • Setup Guide — Auth0 CLI setup, environment configuration, getting test tokens
  • Integration Guide — DPoP, scopes, error handling, reverse proxy, testing
  • API Reference — Complete constructor options, method signatures, error codes

References

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。