> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# FastAPI API

> Python の FastAPI バックエンドに Auth0 JWT 認証を追加し、アクセストークンを検証して、audience と スコープ に基づいてエンドポイントへのアクセスを制御する方法を学びます。

> [accordion] AIプロンプト
>
> **AIを使ってAuth0を統合しますか？** このプロンプトをCursor、Windsurf、Copilot、Claude Codeまたはお気に入りのAI搭載IDEに追加して、開発を効率化しましょう。
>
> ```markdown expandable theme={null}
> Integrate the Auth0 FastAPI SDK into a Python API
>
> AI PERSONA & PRIMARY OBJECTIVE
> You are a helpful Auth0 SDK Integration Assistant for FastAPI APIs. Your primary function is to execute commands to set up a Python FastAPI development environment with Auth0 authentication. Your secondary function is to modify the files created during setup.
>
> CRITICAL BEHAVIORAL INSTRUCTIONS
> 1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Python project (requirements.txt, pyproject.toml, or .py files). If it does, skip project creation and work with the existing project.
> 2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete.
> 3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command.
> 4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation.
> 5. SECURITY FIRST: NEVER hardcode Auth0 Domain or Audience values. ALWAYS use environment variables via python-dotenv.
> 6. 🚨 VIRTUAL ENVIRONMENT RULE: ALWAYS activate the virtual environment before installing packages or running the server. Never skip venv activation.
>
> EXECUTION FLOW
>
> ⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and verify you're in the correct location.
>
> Step 1: Check for Existing FastAPI Project and Prerequisites
> FIRST, verify prerequisites and check for existing Python project:
>
>   # Check if Python 3.9+ and pip are available
>   python3 --version && pip --version
>
> Then examine the current directory:
>
>   # 既存のPythonプロジェクトを確認する
>   if [ -f "requirements.txt" ] || [ -f "pyproject.toml" ] || [ -f "app.py" ]; then
>     echo "Found existing Python project"
>     ls -la
>   else
>     echo "No Python project found, will create new project"
>   fi
>
> Based on the results:
> - If an existing FastAPI project exists, proceed to Step 1b (create venv and install dependencies only)
> - If no project exists, proceed to Step 1a (create new project structure)
>
> Step 1a: Create New FastAPI Project
> If no existing project, create project structure:
>
>   mkdir my-fastapi-api && cd my-fastapi-api && python3 -m venv venv && source venv/bin/activate
>
> ⚠️ WINDOWS USERS: Use `venv\Scripts\activate` instead of `source venv/bin/activate`
>
> Step 1b: Work with Existing Project
> If project exists, create and activate virtual environment:
>
>   python3 -m venv venv && source venv/bin/activate
>
> Step 2: Install Dependencies
> Create requirements.txt with the following content:
>
>   cat > requirements.txt << 'EOF'
>   fastapi>=0.115.0
>   uvicorn[standard]>=0.34.0
>   auth0-fastapi-api>=1.0.0b5
>   python-dotenv>=1.0.0
>   EOF
>
> Then install dependencies (MUST be in activated venv):
>
>   pip install -r requirements.txt
>
> Step 3: Setup Auth0 API
>
> ⚠️ CRITICAL: Verify you're in the project directory with `pwd` before running Auth0 CLI commands.
>
> Step 3a: Execute Auth0 CLI Setup
>
> If MacOS, execute:
>
>   AUTH0_API_NAME="My FastAPI API" && AUTH0_API_IDENTIFIER="https://my-fastapi-api" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apis create --name "${AUTH0_API_NAME}" --identifier "${AUTH0_API_IDENTIFIER}" --signing-alg RS256 --no-input && echo "AUTH0_DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name')\nAUTH0_AUDIENCE=${AUTH0_API_IDENTIFIER}" > .env
>
> If Windows, execute:
>
>   $ApiName = "My FastAPI API"; $ApiIdentifier = "https://my-fastapi-api"; auth0 login --no-input; auth0 apis create -n $ApiName -i $ApiIdentifier --signing-alg RS256 --no-input; $ActiveTenant = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; "AUTH0_DOMAIN=$ActiveTenant`nAUTH0_AUDIENCE=$ApiIdentifier" | Out-File -FilePath .env -Encoding utf8
>
> Step 3b: Verify .env file was created correctly
>
>   cat .env
>
> Expected output:
>   AUTH0_DOMAIN=your-domain.auth0.com
>   AUTH0_AUDIENCE=https://my-fastapi-api
>
> ⚠️ If AUTH0_DOMAIN is null or missing, manually add your Auth0 domain to the .env file.
>
> Step 3c: Add Permissions in Auth0 Dashboard (Manual Step)
> Inform the user to:
> 1. Navigate to Applications > APIs in Auth0 Dashboard
> 2. Select "My FastAPI API"
> 3. Go to Permissions tab
> 4. Add permissions:
>    - Permission: `read:messages`, Description: "Read messages"
>    - Permission: `write:messages`, Description: "Write messages"
>
> Step 4: Create FastAPI Application with Auth0
> Create app.py with the following content:
>
>   cat > app.py << 'EOF'
>   from fastapi import FastAPI, Depends
>   from fastapi_plugin.fast_api_client import Auth0FastAPI
>   import os
>   from dotenv import load_dotenv
>
>   # Load environment variables
>   load_dotenv()
>
>   app = FastAPI()
>
>   # Initialize Auth0
>   auth0 = Auth0FastAPI(
>       domain=os.environ.get("AUTH0_DOMAIN"),
>       audience=os.environ.get("AUTH0_AUDIENCE")
>   )
>
>   # Public route - no authentication required
>   @app.get("/api/public")
>   async def public():
>       return {
>           "message": "Hello from a public endpoint! You don't need to be authenticated to see this."
>       }
>
>   # Protected route - requires authentication
>   @app.get("/api/private")
>   async def private(claims: dict = Depends(auth0.require_auth())):
>       return {
>           "message": "Hello from a private endpoint! You need to be authenticated to see this.",
>           "user_id": claims.get("sub")
>       }
>
>   # Scoped route - requires specific permission
>   @app.get("/api/private-scoped")
>   async def private_scoped(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
>       return {
>           "message": "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.",
>           "user_id": claims.get("sub")
>       }
>   EOF
>
> Step 5: Run the FastAPI Application
>
> ⚠️ CRITICAL: Verify virtual environment is activated before running uvicorn.
>
>   # Verify venv is activated (you should see (venv) in your prompt)
>   which python
>
>   # Start the server
>   uvicorn app:app --reload
>
> Expected output: Server starts on http://127.0.0.1:8000
>
> Step 6: Test the API
>
> 6a: Test public endpoint (no authentication required):
>
>   curl http://localhost:8000/api/public
>
> 6b: Test protected endpoints (authentication required):
> Inform the user to:
> 1. Get access token from Auth0 Dashboard:
>    - Navigate to Applications > APIs
>    - Select "My FastAPI API"
>    - Click "Test" tab
>    - Click "Copy Token"
>
> 2. Test private endpoint:
>
>   curl -X GET http://localhost:8000/api/private -H 'authorization: Bearer YOUR_ACCESS_TOKEN'
>
> 3. Test scoped endpoint:
>
>   curl -X GET http://localhost:8000/api/private-scoped -H 'authorization: Bearer YOUR_ACCESS_TOKEN'
>
> ANTI-PATTERNS - NEVER DO THESE
>
> 1. ❌ NEVER hardcode Auth0 credentials in Python code
>    - WRONG: auth0 = Auth0FastAPI(domain="dev-example.us.auth0.com", audience="https://my-api")
>    - ✓ CORRECT: Always use environment variables via dotenv
>
> 2. ❌ NEVER skip virtual environment activation
>    - WRONG: Installing packages without activating venv first
>    - ✓ CORRECT: Always activate venv first with `source venv/bin/activate`
>
> 3. ❌ NEVER use multi-line curl commands with backslashes (they often fail)
>    - ✓ CORRECT: Use single-line format: `curl -X GET <url> -H 'authorization: Bearer TOKEN'`
>
> 4. ❌ NEVER proceed if .env file has null values
>    - WRONG: AUTH0_DOMAIN=null in .env file
>    - ✓ CORRECT: Verify .env contains valid Auth0 domain before proceeding
>
> ABSOLUTE REQUIREMENTS
>
> 1. ✓ Virtual environment MUST be activated before pip install
> 2. ✓ .env file MUST contain valid AUTH0_DOMAIN (not null)
> 3. ✓ .env file MUST be added to .gitignore to prevent credential exposure
> 4. ✓ Auth0FastAPI MUST use os.environ.get() for credentials
> 5. ✓ All endpoints requiring authentication MUST use Depends(auth0.require_auth())
>
> COMMON ISSUES & SOLUTIONS
>
> 1. **ModuleNotFoundError: No module named 'fastapi_plugin'**
>    - 原因: 誤った仮想環境が有効化されているか、仮想環境が有効化されていない
>    - 解決策: すべての仮想環境を無効化してから、プロジェクトディレクトリ内の正しい仮想環境を有効化する
>
> 2. **AUTH0_DOMAIN is null in .env**
>    - 原因: Auth0 CLI コマンドがドメインを正しく抽出できない
>    - 解決策: Auth0 Dashboard から .env ファイルにドメインを手動で追加する
>
> 3. **401 Unauthorized - Invalid issuer**
>    - 原因: AUTH0_DOMAIN に https:// プロトコルが含まれている
>    - 解決策: ドメインはプロトコルなしで `dev-example.us.auth0.com` のみを指定する
>
> 4. **401 Unauthorized - Invalid audience**
>    - 原因: AUTH0_AUDIENCE が API 識別子と一致していない
>    - 解決策: AUTH0_AUDIENCE が Auth0 Dashboard の識別子と完全に一致していることを確認する
>
> 5. **403 Forbidden - Insufficient scope**
>    - 原因: アクセストークンに必要なスコープが含まれていない
>    - 解決策: Auth0 Dashboard にパーミッションが存在し、トークンにそれらが含まれていることを確認する
>
> バリデーションチェックリスト
>
> 連携が完了したと見なす前に、以下を確認してください:
> - [ ] 仮想環境が有効化されている（`which python` で確認）
> - [ ] .env ファイルが存在し、有効な AUTH0_DOMAIN が含まれている（null でないこと）
> - [ ] .env が .gitignore に追加されている
> - [ ] app.py が Auth0FastAPI を正しくインポートおよび初期化している
> - [ ] パブリックエンドポイントが認証なしで 200 OK を返す
> - [ ] プライベートエンドポイントがトークンなしで 401 を返す
> - [ ] プライベートエンドポイントが有効なトークンで 200 を返す
> - [ ] スコープが設定されたエンドポイントが必要なスコープなしで 403 を返す
> - [ ] スコープが設定されたエンドポイントが read:messages スコープを含むトークンで 200 を返す
> ```

> [!NOTE]
>
> このQuickstartを進めるには、以下が必要です。
>
> * **Python 3.9** 以上
> * **pip** パッケージマネージャー
> * **jq** - Auth0 CLI の設定に必要
> * FastAPI の基本知識
>
> まだの場合は、[無料の Auth0 アカウントにサインアップ](https://auth0.com/signup)してから進めてください。

このガイドでは、FastAPI API に Auth0 を統合して認証を追加し、エンドポイントを保護する方法を紹介します。

**1. 新しいFastAPIプロジェクトを作成**

FastAPI プロジェクト用の新しいディレクトリを作成し、仮想環境を設定します。

```bash theme={null}
mkdir my-fastapi-api
cd my-fastapi-api
python3 -m venv venv
source venv/bin/activate  # Windowsの場合: venv\Scripts\activate
```

**2. 依存関係のインストール**

以下の依存関係を記述した `requirements.txt` ファイルを作成します。

```txt requirements.txt theme={null}
fastapi>=0.115.0
uvicorn[standard]>=0.34.0
auth0-fastapi-api>=1.0.0b5
python-dotenv>=1.0.0
```

依存関係をインストールします：

```bash theme={null}
pip install -r requirements.txt
```

**3. Auth0 API の設定**

FastAPI アプリケーションを表す Auth0 API を作成する必要があります。

> [tab] Dashboard
>
> 1. Auth0 Dashboard で [Applications > APIs](https://manage.auth0.com/#/apis) に移動します
> 2. **Create API** をクリックします
> 3. API の **Name** を入力します (例: "My FastAPI API")
> 4. **Identifier** に API 識別子を設定します (例: `https://my-fastapi-api`)
> 5. **Signing Algorithm** は RS256 のままにします
> 6. **Create** をクリックします

> [tab] CLI
>
> [Auth0 CLI](https://github.com/auth0/auth0-cli) がインストールされていれば、ターミナルから API を作成し、環境設定を行えます。
>
> ```shellscript Mac theme={null}
> AUTH0_API_NAME="My FastAPI API" && AUTH0_API_IDENTIFIER="https://my-fastapi-api" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apis create --name "${AUTH0_API_NAME}" --identifier "${AUTH0_API_IDENTIFIER}" --signing-alg RS256 --no-input && echo "AUTH0_DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name')\nAUTH0_AUDIENCE=${AUTH0_API_IDENTIFIER}" > .env
> ```
>
> ```powershell Windows theme={null}
> $ApiName = "My FastAPI API"; $ApiIdentifier = "https://my-fastapi-api"; auth0 login --no-input; auth0 apis create -n $ApiName -i $ApiIdentifier --signing-alg RS256 --no-input; $ActiveTenant = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; "AUTH0_DOMAIN=$ActiveTenant`nAUTH0_AUDIENCE=$ApiIdentifier" | Out-File -FilePath .env -Encoding utf8
> ```
>
> これにより API が作成され、Auth0 の設定を含む `.env` ファイルも自動的に生成されます。

> [!NOTE]
>
> **Identifier** は API の一意の識別子です。URL を使用することをおすすめしますが、公開されている URL である必要はありません。Auth0 がその URL を呼び出すことはないためです。また、この値は後から変更できません。

**Domain** と **Identifier** (Audience) の値は控えておいてください。次のステップで必要になります。

**4. API の権限を定義する**

権限 (スコープとも呼ばれます) を使うと、API へのアクセス方法を定義できます。API の権限は Auth0 Dashboard で作成できます。

1. Auth0 Dashboard で API の **Permissions** タブに移動します
2. 次の権限を追加します。
   * `read:messages` (説明: "メッセージの読み取り")
   * `write:messages` (説明: "メッセージの書き込み")

これらの権限は、API 内の特定のエンドポイントへのアクセスを制御するために使用されます。

**5. Auth0のクライアントを設定する**

Auth0の設定を保存するため、プロジェクトのルートディレクトリに `.env` ファイルを作成します。

```txt .env theme={null}
AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
AUTH0_AUDIENCE=YOUR_API_IDENTIFIER
```

`YOUR_AUTH0_DOMAIN` はご利用の Auth0 ドメイン (例: `dev-abc123.us.auth0.com`) に、`YOUR_API_IDENTIFIER` は API 作成時に設定した識別子に置き換えてください。

> [!WARNING]
>
> `.env` ファイルは絶対にバージョン管理にコミットしないでください。資格情報を安全に保つため、`.gitignore` ファイルに追加してください。

次に、`app.py` ファイルを作成し、Auth0 で FastAPI アプリケーションを初期化します。

```python app.py theme={null}
from fastapi import FastAPI, Depends
from fastapi_plugin.fast_api_client import Auth0FastAPI
import os
from dotenv import load_dotenv

# 環境変数を読み込む
load_dotenv()

app = FastAPI()

# Auth0を初期化する
auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE")
)
```

**6. 保護されたルートを作成する**

次のルートを`app.py`ファイルに追加してください。これらのルートは、さまざまなレベルのアクセス制御を示しています。

```python app.py theme={null}
from fastapi import FastAPI, Depends
from fastapi_plugin.fast_api_client import Auth0FastAPI
import os
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

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

# パブリックルート - 認証不要
@app.get("/api/public")
async def public():
    return {
        "message": "Hello from a public endpoint! You don't need to be authenticated to see this."
    }

# 保護されたルート - 認証が必要
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
    return {
        "message": "Hello from a private endpoint! You need to be authenticated to see this.",
        "user_id": claims.get("sub")
    }

# スコープが設定されたルート - 特定の権限が必要
@app.get("/api/private-scoped")
async def private_scoped(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
    return {
        "message": "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.",
        "user_id": claims.get("sub")
    }
```

`require_auth()` メソッドは、Authorizationヘッダーで送信されたアクセストークンを検証します。`scopes` パラメータを指定して呼び出すと、トークンに指定された権限が含まれているかどうかも確認します。

**7. APIを実行**

FastAPIアプリケーションを起動します:

```bash theme={null}
uvicorn app:app --reload
```

API は現在 `http://localhost:8000` で実行されています。

> [!TIP]
>
> ブラウザーで `http://localhost:8000/api/public` にアクセスしてください。認証なしで公開メッセージが表示されるはずです。

***

## APIをテストする

保護されたエンドポイントをテストするには、Auth0からアクセストークンを取得する必要があります。

### アクセストークンを取得する

テスト用のアクセストークンを取得する最も簡単な方法は、Auth0 Dashboard を使うことです。

1. Auth0 Dashboard で [Applications > APIs](https://manage.auth0.com/#/apis) に移動します
2. API を選択します
3. **Test** タブをクリックします
4. **Asking Auth0 for tokens from my application** セクションで **Copy Token** をクリックします

### API を呼び出す

アクセストークンを使用して、保護されたエンドポイントを呼び出します。

```bash theme={null}
curl -X GET http://localhost:8000/api/private -H 'authorization: Bearer YOUR_ACCESS_TOKEN'
```

プライベートメッセージと user ID を含むレスポンスが返されます。

スコープが設定されたエンドポイントをテストするには、トークンに `read:messages` スコープが含まれていることを確認してください。

```bash theme={null}
curl -X GET http://localhost:8000/api/private-scoped -H 'authorization: Bearer YOUR_ACCESS_TOKEN'
```

お使いのトークンに必要なスコープが含まれていない場合は、403 Forbidden レスポンスが返されます。

***

## 高度な使い方

> [accordion] カスタムクレームを検証する
>
> [Auth0 Actions](/docs/docs/ja-jp/customize/actions) を通じてアクセストークンに追加されたカスタムクレームにアクセスできます。
>
> ルートハンドラーでは、次のようにカスタムクレームにアクセスします。
>
> ```python theme={null}
> @app.get("/api/profile")
> async def profile(claims: dict = Depends(auth0.require_auth())):
>     return {
>         "user_id": claims.get("sub"),
>         "email": claims.get("email"),
>         "permissions": claims.get("permissions", []),
>         "custom_claim": claims.get("https://myapp.example.com/custom_claim")
>     }
> ```
>
> アクセストークンにカスタムクレームを追加するには、Auth0 Action を作成します。
>
> 1. Auth0 Dashboard で **Actions > Library** に移動します
> 2. **Create Action** をクリックします
> 3. **Create Custom Action** を選択します
> 4. Action に名前を付け、**Login / Post Login** トリガーを選択します
> 5. カスタムクレームを追加します
>
> ```javascript theme={null}
> exports.onExecutePostLogin = async (event, api) => {
>   const namespace = 'https://myapp.example.com';
>
>   if (event.authorization) {
>     // アクセストークンにカスタムクレームを追加
>     api.accessToken.setCustomClaim(`${namespace}/roles`, event.user.app_metadata.roles || []);
>   }
> };
> ```
>
> 6. **Deploy** をクリックし、その Action をログインフローに追加します
>
> > [!NOTE]
> >
> > カスタムクレームは、標準クレームとの競合を避けるため、名前空間付き形式 (例: `https://myapp.example.com/claim_name`) を使用する必要があります。

> [accordion] クレームを使用せずにエンドポイントを保護する
>
> エンドポイントを保護したいものの、クレームにアクセスする必要がない場合は、`dependencies` パラメーターを使用できます。
>
> ```python theme={null}
> @app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
> async def protected():
>     return {"message": "This endpoint is protected"}
> ```
>
> これによりアクセストークンは検証されますが、クレームは関数に注入されません。

> [accordion] DPoP サポート
>
> > [!NOTE]
> >
> > DPoP (Demonstrating Proof-of-Possession) は現在 [早期アクセス](/docs/docs/ja-jp/troubleshoot/product-lifecycle/product-release-stages) 段階です。テナント で有効にするには、[Auth0 Support](https://support.auth0.com/) にお問い合わせください。
>
> DPoP は、アクセストークンをそれを要求したクライアントに暗号学的に関連付けることで、セキュリティを強化します。これにより、トークン の盗難やリプレイ攻撃を防止できます。
>
> SDK ではデフォルトで DPoP サポートが有効になっています。DPoP の動作は設定できます。
>
> ```python theme={null}
> auth0 = Auth0FastAPI(
>     domain=os.environ.get("AUTH0_DOMAIN"),
>     audience=os.environ.get("AUTH0_AUDIENCE"),
>     dpop_enabled=True,      # DPoP を有効化（デフォルト: True）
>     dpop_required=False     # DPoP を必須化（デフォルト: False）
> )
> ```
>
> **混合モード** (デフォルト) では Bearer トークン と DPoP トークン の両方を受け入れます。
>
> ```python theme={null}
> auth0 = Auth0FastAPI(
>     domain=os.environ.get("AUTH0_DOMAIN"),
>     audience=os.environ.get("AUTH0_AUDIENCE"),
>     dpop_enabled=True,
>     dpop_required=False
> )
> ```
>
> **DPoP 専用モード**では Bearer トークン を拒否します。
>
> ```python theme={null}
> auth0 = Auth0FastAPI(
>     domain=os.environ.get("AUTH0_DOMAIN"),
>     audience=os.environ.get("AUTH0_AUDIENCE"),
>     dpop_required=True
> )
> ```
>
> DPoP を使用する場合、クライアントは `Authorization: DPoP <token>` と `DPoP: <proof>` の両方の ヘッダー を含める必要があります。SDK は DPoP proof を自動的に検証し、それをアクセストークンにバインドします。

> [accordion] リバースプロキシ向けの設定
>
> > [!WARNING]
> >
> > `trust_proxy` は、アプリケーションが信頼できるリバースプロキシの背後にある場合にのみ有効にしてください。インターネットに直接公開されているアプリケーションでは、絶対に有効にしないでください。
>
> アプリケーションがリバースプロキシ (nginx、AWS ALB など) の背後で動作している場合、DPoP のバリデーションを正しく機能させるにはプロキシ信頼を有効にする必要があります。
>
> ```python theme={null}
> from fastapi import FastAPI
>
> app = FastAPI()
>
> # プロキシ信頼を有効化
> app.state.trust_proxy = True
>
> auth0 = Auth0FastAPI(
>     domain=os.environ.get("AUTH0_DOMAIN"),
>     audience=os.environ.get("AUTH0_AUDIENCE")
> )
> ```
>
> 必要な ヘッダー を転送するよう、リバースプロキシを設定します。
>
> ```nginx theme={null}
> location /api {
>     proxy_pass http://localhost:8000;
>     proxy_set_header X-Forwarded-Proto $scheme;
>     proxy_set_header X-Forwarded-Host $host;
>     proxy_set_header X-Forwarded-Prefix /api;
> }
> ```
>
> これは DPoP のバリデーションに不可欠です。SDK はクライアントが使用した正確な URL と一致させる必要があるためです。プロキシ信頼が有効でないと、アプリケーションには内部 URL が見える一方で、DPoP proof は外部 URL を参照するため、バリデーションに失敗します。

> [accordion] エラー処理
>
> SDK は、認証エラーが発生すると `HTTPException` を送出します。FastAPI はこれらを自動的に処理し、クライアントに適切な HTTP レスポンスを返します。
>
> 必要に応じて、カスタムのエラー処理を実装することもできます。
>
> ```python theme={null}
> from fastapi import Request
> from fastapi.responses import JSONResponse
> from fastapi.exceptions import HTTPException
>
> @app.exception_handler(HTTPException)
> async def custom_http_exception_handler(request: Request, exc: HTTPException):
>     if exc.status_code in [401, 403]:
>         return JSONResponse(
>             status_code=exc.status_code,
>             content={
>                 "error": "authentication_failed",
>                 "message": "You must be authenticated to access this resource",
>                 "details": exc.detail
>             }
>         )
>     return JSONResponse(
>         status_code=exc.status_code,
>         content={"detail": exc.detail}
>     )
> ```
>
> 認証エラーには、次のようなものがあります。
>
> * **401 Unauthorized**: アクセス トークンが存在しない、無効である、または期限切れ
> * **403 Forbidden**: トークンは有効だが、必要な権限 (スコープ) が不足している

***

## よくある問題

> [accordion] 401 Unauthorized - 無効な audience
>
> **問題**: "Invalid audience" エラーによりトークンの検証に失敗します。
>
> **解決策**: `.env` ファイルの `AUTH0_AUDIENCE` が、Auth0 Dashboard で API に設定した **Identifier** と完全に一致していることを確認してください。
>
> 1. Auth0 Dashboard を開き、**Applications > APIs** に移動します
> 2. API を選択します
> 3. **設定** タブで **Identifier** の値を確認します
> 4. `.env` ファイルを更新します:
>    ```txt theme={null}
>    AUTH0_AUDIENCE=https://your-exact-api-identifier
>    ```
> 5. アプリケーションを再起動します

> [accordion] 401 Unauthorized - 無効な発行者
>
> **問題**: "Invalid issuer" エラーによりトークンの検証に失敗します。
>
> **解決策**: `AUTH0_DOMAIN` が正しく、`https://` プロトコルを含んでいないことを確認してください。
>
> ドメインは `https://dev-abc123.us.auth0.com` ではなく、`dev-abc123.us.auth0.com` のようになっている必要があります。
>
> `.env` ファイルを更新します:
>
> ```txt theme={null}
> AUTH0_DOMAIN=dev-abc123.us.auth0.com
> ```

> [accordion] 403 Forbidden - スコープ不足
>
> **問題**: 有効なアクセストークンを使用していても、保護されたエンドポイントが 403 を返します。
>
> **解決策**: アクセストークンに必要なスコープが含まれていません。
>
> 1. エンドポイントに必要なスコープを確認します
> 2. トークンをリクエストするときに、必要なスコープを含めていることを確認します
> 3. Auth0 Dashboard の API の **Permissions** タブに、そのスコープが存在することを確認します
> 4. [jwt.io](https://jwt.io) でトークンをデコードし、必要な値を持つ `scope` クレームが含まれていることを確認します

> [accordion] ModuleNotFoundError: No module named 'fastapi\_plugin'
>
> **問題**: Python が Auth0 FastAPI SDK を見つけられません。
>
> **解決策**: SDK が現在有効な仮想環境にインストールされていることを確認してください。
>
> ```bash theme={null}
> # 仮想環境を有効化
> source venv/bin/activate  # Windows: venv\Scripts\activate
>
> # SDK をインストール
> pip install auth0-fastapi-api
>
> # インストールを確認
> pip show auth0-fastapi-api
> ```

> [accordion] Auth0 に接続できない（JWKS の取得に失敗）
>
> **問題**: アプリケーションが Auth0 から署名鍵を取得できません。
>
> **解決策**: ネットワーク接続とドメイン設定を確認してください。
>
> 1. ドメインにアクセスできることを確認します:
>    ```bash theme={null}
>    curl https://YOUR_DOMAIN/.well-known/openid-configuration
>    ```
>
> 2. `*.auth0.com` への HTTPS アウトバウンド接続 (ポート 443) がファイアウォールで許可されていることを確認します
>
> 3. 企業のプロキシ配下にある場合は、`HTTP_PROXY` と `HTTPS_PROXY` 環境変数を設定します

> [accordion] DPoP のバリデーションに失敗する
>
> **問題**: DPoP 認証で、URL またはプルーフのバリデーションに関するエラーが返されます。
>
> **解決策**:
>
> 1. リバースプロキシの背後にある場合は、プロキシの信頼を有効化します:
>    ```python theme={null}
>    app.state.trust_proxy = True
>    ```
>
> 2. プロキシが次のヘッダーを転送していることを確認します:
>    * `X-Forwarded-Proto`
>    * `X-Forwarded-Host`
>    * `X-Forwarded-Prefix`
>
> 3. テナントで DPoP が有効になっていることを確認します (Auth0 Support にお問い合わせください)
>
> 4. DPoP proof の `htu` クレームがリクエスト URL と完全に一致していることを確認します

***

## 次のステップ

> [card] [SDK ドキュメント](https://github.com/auth0/auth0-fastapi-api)
>
> 高度な設定や実装例については、GitHub の Auth0 FastAPI SDK をご覧ください

> [card] [スコープと権限](/docs/docs/ja-jp/get-started/apis/scopes)
>
> きめ細かなアクセス制御のためにスコープを定義して活用する方法を学びましょう

> [card] [Auth0 Actions](/docs/docs/ja-jp/customize/actions)
>
> 認証フローをカスタマイズし、トークンにカスタムクレームを追加する方法を学びましょう

> [card] [FastAPI ドキュメント](https://fastapi.tiangolo.com/)
>
> FastAPI の機能、非同期パターン、ベストプラクティスについて詳しく学びましょう

> [card] [API 認可](/docs/docs/ja-jp/authorization)
>
> API にロールベースのアクセス制御 (RBAC) を実装する方法を学びましょう

> [card] [本番環境にデプロイ](/docs/docs/ja-jp/deploy)
>
> Auth0 を使用した FastAPI アプリケーションの本番デプロイのベストプラクティス
