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

> 保護されたエンドポイントを持つFastAPIにAuth0 JWT認証を追加する

# FastAPI API

export const HowToSchema = () => <script type="application/ld+json">
    {'{"@context":"https://schema.org","@type":"HowTo"}'}
  </script>;

<HowToSchema />

<Accordion title="AI プロンプト" defaultOpen icon="microchip-ai" iconType="sharp-solid">
  **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:

    # Python 3.9 以上と pip が利用可能か確認
    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_dotenv()

    app = FastAPI()

    # Auth0 を初期化
    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")
        }
    EOF

  Step 5: Run the FastAPI Application

  ⚠️ CRITICAL: Verify virtual environment is activated before running uvicorn.

    # venv が有効化されていることを確認（プロンプトに (venv) と表示されます）
    which python

    # サーバーを起動
    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 に Permissions が存在し、トークンにそれらが含まれていることを確認する

  検証チェックリスト

  統合が完了したとみなす前に、以下を確認してください:
  - [ ] 仮想環境が有効化されている（`which python` で確認）
  - [ ] .env ファイルが存在し、有効な AUTH0_DOMAIN が含まれている（null でないこと）
  - [ ] .env が .gitignore に追加されている
  - [ ] app.py が Auth0FastAPI を正しくインポートおよび初期化している
  - [ ] パブリックエンドポイントが認証なしで 200 OK を返す
  - [ ] プライベートエンドポイントがトークンなしで 401 を返す
  - [ ] プライベートエンドポイントが有効なトークンで 200 を返す
  - [ ] スコープ付きエンドポイントが必要なスコープなしで 403 を返す
  - [ ] スコープ付きエンドポイントが read:messages スコープを含むトークンで 200 を返す
  ```
</Accordion>

<Note>
  このクイックスタートを進めるには、以下が必要です。

  * **Python 3.9** 以上
  * **pip** パッケージマネージャー
  * **jq** - Auth0 CLI のセットアップに必要
  * FastAPI の基本的な知識

  まだお持ちでない場合は、手順に沿って進められるよう、[無料の Auth0 アカウントにサインアップ](https://auth0.com/signup)してください。
</Note>

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

<Steps>
  <Step title="新しいFastAPIプロジェクトを作成する" stepNumber={1}>
    FastAPI プロジェクト用の新しいディレクトリを作成し、仮想環境をセットアップします。

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

  <Step title="依存関係をインストール" stepNumber={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
    ```
  </Step>

  <Step title="Auth0 APIを設定する" stepNumber={3}>
    FastAPI アプリケーションを表す Auth0 API を作成する必要があります。

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

      <Tab title="CLI">
        [Auth0 CLI](https://github.com/auth0/auth0-cli) がインストールされている場合は、ターミナルから API を作成し、環境設定を行えます。

        <CodeGroup>
          ```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
          ```
        </CodeGroup>

        これにより API が作成され、Auth0 の設定を含む `.env` ファイルが自動的に生成されます。
      </Tab>
    </Tabs>

    <Info>
      **Identifier** は API の一意の識別子です。URL を使用することを推奨しますが、公開されている URL である必要はありません。Auth0 からこの URL が呼び出されることはありません。この値は後から変更できません。
    </Info>

    **ドメイン** と **Identifier** (オーディエンス) の値を控えておいてください。これらは次の手順で必要になります。
  </Step>

  <Step title="API の権限を定義する" stepNumber={4}>
    Permissions (スコープとも呼ばれます) を使用すると、API へのアクセス方法を定義できます。API の Permissions は Auth0 Dashboard で作成できます。

    1. Auth0 Dashboard で、API の **Permissions** タブに移動します
    2. 次の Permissions を追加します:
       * 説明が "Read messages" の `read:messages`
       * 説明が "Write messages" の `write:messages`

    これらの Permissions は、API 内の特定のエンドポイントへのアクセスを制御するために使用します。
  </Step>

  <Step title="Auth0のクライアントを設定する" stepNumber={5}>
    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` ファイルに追加してください。
    </Warning>

    次に、`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")
    )
    ```
  </Step>

  <Step title="保護されたルートを作成" stepNumber={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` パラメーターを指定して呼び出すと、トークンに指定した権限が含まれていることも検証します。
  </Step>

  <Step title="API を起動する" stepNumber={7}>
    FastAPI アプリケーションを起動します。

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

    API は `http://localhost:8000` で実行中です。

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

***

<div id="test-your-api">
  ## API をテストする
</div>

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

<div id="get-an-access-token">
  ### アクセストークンを取得する
</div>

テスト用のアクセストークンを取得する最も簡単な方法は、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** をクリックします

<div id="call-your-api">
  ### API を呼び出す
</div>

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

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

非公開メッセージとユーザー ID を含むレスポンスを受け取るはずです。

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

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

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

***

<div id="advanced-usage">
  ## 高度な使用方法
</div>

<Accordion title="カスタムクレームを検証する">
  [Auth0 Actions](https://auth0.com/docs/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. **Build from scratch** を選択します
  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 を Login フローに追加します

  <Info>
    標準クレームとの競合を避けるため、カスタムクレームには名前空間付きの形式 (例: `https://myapp.example.com/claim_name`) を使用する必要があります。
  </Info>
</Accordion>

<Accordion title="クレームを使用せずにエンドポイントを保護する">
  エンドポイントを保護する必要はあってもクレームにアクセスする必要がない場合は、`dependencies` パラメーターを使用できます。

  ```python theme={null}
  @app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
  async def protected():
      return {"message": "This endpoint is protected"}
  ```

  これによりアクセストークンは検証されますが、クレームは関数に渡されません。
</Accordion>

<Accordion title="DPoP サポート">
  <Info>
    DPoP (Demonstrating Proof-of-Possession) は現在 [Early Access](https://auth0.com/docs/troubleshoot/product-lifecycle/product-release-stages) 段階です。テナントで有効にするには、[Auth0 support](https://support.auth0.com/) にお問い合わせください。
  </Info>

  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>

<Accordion title="リバースプロキシ向けの設定">
  <Warning>
    `trust_proxy` は、アプリケーションが信頼できるリバースプロキシの背後にある場合にのみ有効にしてください。インターネットに直接公開されているアプリケーションでは、絶対に有効にしないでください。
  </Warning>

  アプリケーションがリバースプロキシ (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>

<Accordion title="エラー処理">
  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>

***

<div id="common-issues">
  ## よくある問題
</div>

<AccordionGroup>
  <Accordion title="401 Unauthorized - オーディエンスが無効">
    **問題**: トークンの検証が "Invalid audience" エラーで失敗します。

    **解決策**: `.env` ファイル内の `AUTH0_AUDIENCE` が、Auth0 Dashboard で API に設定した **Identifier** と完全に一致していることを確認してください。

    1. Auth0 Dashboard を開き、**Applications > APIs** に移動します
    2. 対象の API を選択します
    3. Settings タブで **Identifier** の値を確認します
    4. `.env` ファイルを更新します:
       ```txt theme={null}
       AUTH0_AUDIENCE=https://your-exact-api-identifier
       ```
    5. アプリケーションを再起動します
  </Accordion>

  <Accordion title="401 Unauthorized - issuer が無効">
    **問題**: トークンの検証が "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>

  <Accordion title="403 Forbidden - スコープが不足している">
    **問題**: 有効なアクセストークンを使用していても、保護されたエンドポイントから 403 が返されます。

    **解決策**: アクセストークンに必要なスコープが含まれていません。

    1. エンドポイントに必要なスコープを確認します
    2. トークンをリクエストする際に、必要なスコープを含めるようにします
    3. Auth0 Dashboard の API の Permissions タブに、そのスコープが存在することを確認します
    4. [jwt.io](https://jwt.io) でトークンをデコードし、必要な値を含む `scope` クレームがあることを確認します
  </Accordion>

  <Accordion title="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>

  <Accordion title="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>

  <Accordion title="DPoP 検証が失敗する">
    **問題**: DPoP 認証で、URL または proof の検証に関するエラーが返されます。

    **解決策**:

    1. リバースプロキシの配下にある場合は、プロキシの信頼設定を有効にします:
       ```python theme={null}
       app.state.trust_proxy = True
       ```

    2. プロキシが次のヘッダーを転送していることを確認します:
       * `X-Forwarded-Proto`
       * `X-Forwarded-Host`
       * `X-Forwarded-Prefix`

    3. テナントで DPoP が有効になっていることを確認します (Auth0 サポートにお問い合わせください)

    4. DPoP proof の `htu` クレームがリクエスト URL と完全に一致していることを確認します
  </Accordion>
</AccordionGroup>

***

<div id="next-steps">
  ## 次のステップ
</div>

<CardGroup cols={3}>
  <Card title="SDK ドキュメント" icon="github" href="https://github.com/auth0/auth0-fastapi-api">
    高度な設定や実装例については、GitHub の Auth0 FastAPI SDK を参照してください
  </Card>

  <Card title="スコープと権限" icon="lock" href="https://auth0.com/docs/get-started/apis/scopes">
    きめ細かなアクセス制御のために、スコープを定義して活用する方法を学びます
  </Card>

  <Card title="Auth0 Actions" icon="bolt" href="https://auth0.com/docs/customize/actions">
    認証フローをカスタマイズし、トークンにカスタムクレームを追加します
  </Card>

  <Card title="FastAPI ドキュメント" icon="book" href="https://fastapi.tiangolo.com/">
    FastAPI の機能、非同期パターン、ベストプラクティスについて詳しく学びます
  </Card>

  <Card title="API 認可" icon="shield-check" href="https://auth0.com/docs/authorization">
    API にロールベースアクセス制御 (RBAC) を実装します
  </Card>

  <Card title="本番環境にデプロイ" icon="server" href="https://auth0.com/docs/deploy">
    Auth0 を使用した FastAPI アプリケーションのデプロイに関するベストプラクティス
  </Card>
</CardGroup>
