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

# Flask API

> このガイドでは、Flask で構築した新規または既存の Python API に Auth0 を統合する方法を紹介します。

> [!NOTE]
>
> **前提条件:** 始める前に、以下がインストールされていることを確認してください。
>
> * **Python 3.9** 以上
> * **pip** または Poetry パッケージマネージャー
> * **[jq](https://jqlang.org/)** - Auth0 CLI の設定に必要です
> * お好みのコードエディター
>
> **Flask のバージョン互換性:** この Quickstart では、ネイティブの async サポートを利用するために **Flask 3.0** 以上が必要です。

## はじめに

このガイドでは、[Flask](https://flask.palletsprojects.com/) で構築した新規または既存の Python API に Auth0 を統合する方法を説明します。

**1. Flask の新しいプロジェクトを作成する**

Flask API 用に新しいディレクトリを作成します:

```bash theme={null}
mkdir flask-auth0-api
cd flask-auth0-api
```

仮想環境を作成し、アクティベートします:

```bash theme={null}
python -m venv venv
source venv/bin/activate  # Windowsの場合: venv\Scripts\activate
```

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

以下の依存パッケージを記載した `requirements.txt` ファイルを作成します:

```txt requirements.txt theme={null}
flask>=3.0
auth0-api-python
python-dotenv
```

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

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

**3. Auth0 API の設定**

次に、Auth0 テナントに新しい API を作成し、アプリケーションを設定します。

この作業は、CLI コマンドを実行して自動で行うことも、Auth0 Dashboard から手動で行うこともできます。

> [tab] Dashboard
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/) → **アプリケーション** → **APIs** に移動します
>
> 2. **Create API** をクリックします
>
> 3. API の詳細を入力します。
>    * **Name**: `My Flask API`
>    * **Identifier**: `https://my-flask-api` (これが audience になります)
>    * **Signing Algorithm**: **RS256**
>
> 4. **Create** をクリックします
>
> 5. Auth0 Dashboard で **Domain** をコピーします (**アプリケーション** → **アプリケーション** → **\[Your App]** → **設定** にあります)
>
> 6. 作成した **Identifier** をコピーします (これが audience です)
>
> > [!NOTE]
> >
> > **Domain** には `https://` を含めず、ドメイン名のみを使用してください (例: `your-tenant.auth0.com`) 。
> >
> > **Audience** (API 識別子) は API の一意の識別子で、有効な URI であれば任意の値を指定できます。

> [tab] CLI
>
> Auth0 API を作成し、`.env` ファイルを生成するには、プロジェクトのルートディレクトリで次のシェルコマンドを実行します。
>
> ```shellscript Mac theme={null}
> AUTH0_API_NAME="My Flask API" && AUTH0_API_IDENTIFIER="https://my-flask-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 --json > auth0-api-details.json && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && AUDIENCE=$(jq -r '.identifier' auth0-api-details.json) && echo "AUTH0_DOMAIN=${DOMAIN}" > .env && echo "AUTH0_AUDIENCE=${AUDIENCE}" >> .env && rm auth0-api-details.json && echo ".env file created with your Auth0 API details:" && cat .env
> ```
>
> ```shellscript Windows theme={null}
> $ApiName = "My Flask API"; $ApiIdentifier = "https://my-flask-api"; winget install Auth0.CLI; auth0 login --no-input; auth0 apis create -n "$ApiName" -i "$ApiIdentifier" --signing-alg RS256 --json | Set-Content -Path auth0-api-details.json; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; $Audience = (Get-Content -Raw auth0-api-details.json | ConvertFrom-Json).identifier; Set-Content -Path .env -Value "AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "AUTH0_AUDIENCE=$Audience"; Remove-Item auth0-api-details.json; Write-Output ".env file created with your Auth0 API details:"; Get-Content .env
> ```

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

特定のリソースへのアクセスを制御するために、API の権限 (スコープ) を設定します。

1. [Auth0 Dashboard](https://manage.auth0.com/) で、**アプリケーション** → **APIs** に移動します
2. API (`My Flask API`) を選択します
3. **Permissions** タブを開きます
4. **Add Permission** をクリックします
5. 次の権限を追加します。
   * **Permission (Scope)**: `read:messages`
   * **Description**: `Read messages`
6. **Add** をクリックします

> [!NOTE]
>
> Permissions では、その API に対して実行できる操作を定義します。`write:messages`、`delete:messages` など、複数の権限を追加できます。この Quickstart の `/api/private-scoped` エンドポイントには、`read:messages` 権限が必要です。

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

> [!NOTE]
>
> ステップ3で**CLI**の方法を使用した場合、`.env`ファイルは自動的に作成されています。以下の`app.py`ファイルの作成に進んでください。

**Auth0 Dashboard**の方法を使用した場合は、Auth0の設定を保存するため、プロジェクトのルートディレクトリに`.env`ファイルを作成してください。

```bash .env theme={null}
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://my-flask-api
```

> [!WARNING]
>
> `your-tenant.us.auth0.com` は実際の Auth0 ドメインに置き換え、`API_IDENTIFIER` はダッシュボードにある API 識別子に合わせて更新してください。

`app.py` ファイルを作成し、Auth0 API クライアントを設定します。

```python app.py theme={null}
import os
import asyncio
from flask import Flask, request, jsonify, g
from functools import wraps
from dotenv import load_dotenv
from auth0_api_python import ApiClient, ApiClientOptions
from auth0_api_python.errors import BaseAuthError

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

app = Flask(__name__)

# Auth0 APIクライアントを初期化する（シングルトン - 一度だけ作成）
api_client = ApiClient(ApiClientOptions(
    domain=os.getenv("AUTH0_DOMAIN"),
    audience=os.getenv("AUTH0_AUDIENCE")
))
```

**5. 保護されたルートを作成**

ルートを保護するデコレーターを追加し、公開エンドポイントと非公開エンドポイントを作成します:

```python app.py theme={null}
# 認証デコレーター
def require_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        auth_header = request.headers.get("Authorization", "")
        
        if not auth_header.startswith("Bearer "):
            return jsonify({"error": "Missing or invalid authorization header"}), 401
        
        token = auth_header.split(" ")[1]
        
        try:
            claims = asyncio.run(api_client.verify_access_token(token))
            g.user_claims = claims
            return f(*args, **kwargs)
        except BaseAuthError as e:
            return (
                jsonify({"error": str(e)}),
                e.get_status_code(),
                e.get_headers()
            )
    
    return decorated_function


# 公開エンドポイント - 認証不要
@app.route("/api/public", methods=["GET"])
def public():
    return jsonify({"message": "This endpoint is public"})


# 保護されたエンドポイント - 認証が必要
@app.route("/api/private", methods=["GET"])
@require_auth
def private():
    return jsonify({
        "message": "This endpoint requires authentication",
        "user": g.user_claims.get("sub")
    })


# パーミッションのバリデーションが必要な保護されたエンドポイント
@app.route("/api/private-scoped", methods=["GET"])
@require_auth
def private_scoped():
    scopes = g.user_claims.get("scope", "").split()
    
    if "read:messages" not in scopes:
        return jsonify({"error": "Insufficient permissions"}), 403
    
    return jsonify({
        "message": "Private scoped endpoint - read:messages permission granted",
        "user": g.user_claims.get("sub")
    })


if __name__ == "__main__":
    app.run(debug=True, port=5000)
```

**6. APIを実行する**

Flask アプリケーションを起動します。

```bash theme={null}
python app.py
```

これでAPIは `http://localhost:5000` で実行中です。

> [!TIP]
>
> **チェックポイント**
>
> これで、3 つのエンドポイントを備えた Auth0 保護の Flask API が localhost 上で完全に動作しているはずです。
>
> * `/api/public` - 認証なしでアクセス可能
> * `/api/private` - 有効な Auth0 アクセストークンが必要
> * `/api/private-scoped` - 認証と `read:messages` 権限が必要

## APIをテストする

保護されたエンドポイントをテストするには、アクセストークンが必要です。

### テスト用トークンを取得する

1. [Auth0 Dashboard](https://manage.auth0.com/)に移動します
2. **アプリケーション → APIs** に移動します
3. 使用するAPIを選択します
4. **Test** タブを開きます
5. アクセストークンをコピーします

### リクエストを送信する

パブリックエンドポイント (トークン不要) をテストします：

```bash theme={null}
curl http://localhost:5000/api/public
```

保護されたエンドポイントをテストします (トークンが必要です) ：

```bash theme={null}
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  http://localhost:5000/api/private
```

`YOUR_ACCESS_TOKEN` を Auth0 Dashboard からコピーしたトークンに置き換えます。

## 高度な使用方法

> [accordion] カスタムクレームの検証
>
> アクセストークンに特定のクレームが含まれていることを必須にします。
>
> ```python theme={null}
> try:
>     claims = await api_client.verify_access_token(
>         access_token=token,
>         required_claims=["email_verified", "org_id"]
>     )
> except BaseAuthError as e:
>     return jsonify({"error": "Missing required claims"}), 401
> ```

> [accordion] DPoP認証
>
> セキュリティをさらに強化するには、DPoP (Demonstrating Proof-of-Possession) を有効にします。DPoP は、アクセストークンを暗号キーに関連付けることで OAuth 2.0 を強化します。
>
> ```python theme={null}
> import asyncio
>
>
> # DPoP を有効にして API クライアントを設定します（Allowed モード）
> api_client = ApiClient(ApiClientOptions(
>     domain=os.getenv("AUTH0_DOMAIN"),
>     audience=os.getenv("AUTH0_AUDIENCE"),
>     dpop_enabled=True,   # デフォルト - DPoP サポートを有効にします
>     dpop_required=False  # デフォルト - Bearer トークンと DPoP トークンの両方を許可します
> ))
>
> # Required モードの場合（DPoP のみ、Bearer トークンは拒否）
> # dpop_required=True
>
> # DPoP 対応デコレーター
> def require_auth_dpop(f):
>     @wraps(f)
>     def decorated_function(*args, **kwargs):
>         headers = {
>             "authorization": request.headers.get("Authorization", ""),
>             "dpop": request.headers.get("DPoP", "")  # DPoP proof ヘッダー
>         }
>
>         try:
>             # verify_request() は Bearer または DPoP スキームを自動的に検出します
>             claims = asyncio.run(api_client.verify_request(
>                 headers=headers,
>                 http_method=request.method,
>                 http_url=request.url
>             ))
>             g.user_claims = claims
>             return f(*args, **kwargs)
>         except BaseAuthError as e:
>             return jsonify({"error": str(e)}), e.get_status_code(), e.get_headers()
>
>     return decorated_function
>
> @app.route("/api/dpop-protected")
> @require_auth_dpop
> def dpop_protected():
>     return jsonify({
>         "message": "Successfully authenticated with DPoP or Bearer",
>         "user": g.user_claims.get("sub")
>     })
> ```
>
> > [!NOTE]
> >
> > `verify_request()` メソッドは、リクエストで Bearer 認証と DPoP 認証のどちらが使われているかを自動的に検出します。DPoP が使用されている場合は、RFC 9449 に従ってアクセストークンと DPoP proof の両方を検証します。

> [accordion] スコープベースの認可
>
> 特定のスコープを確認するデコレーターを作成します。
>
> ```python theme={null}
> def require_scope(required_scope):
>     def decorator(f):
>         @wraps(f)
>         async def wrapper(*args, **kwargs):
>             if not hasattr(g, "user_claims"):
>                 return jsonify({"error": "Unauthorized"}), 401
>
>             scopes = g.user_claims.get("scope", "").split()
>
>             if required_scope not in scopes:
>                 return jsonify({"error": "Insufficient permissions"}), 403
>
>             return await f(*args, **kwargs)
>         return wrapper
>     return decorator
>
>
> @app.route("/api/admin")
> @require_auth
> @require_scope("admin:write")
> async def admin_endpoint():
>     return jsonify({"message": "Admin access granted"})
> ```

> [accordion] エラー処理のベストプラクティス
>
> 具体的なエラー種別に対応した、包括的なエラー処理を実装します。
>
> ```python theme={null}
> from auth0_api_python.errors import (
>     BaseAuthError,
>     VerifyAccessTokenError,
>     GetTokenByExchangeProfileError,
>     ApiError
> )
>
> @app.errorhandler(BaseAuthError)
> def handle_auth_error(error):
>     """すべてのAuth0認証エラーを処理"""
>     return jsonify({
>         "error": error.get_error_code(),
>         "error_description": str(error)
>     }), error.get_status_code(), error.get_headers()
>
>
> @app.errorhandler(VerifyAccessTokenError)
> def handle_token_verification_error(error):
>     """特にトークン検証の失敗を処理"""
>     app.logger.warning(f"Token verification failed: {str(error)}")
>     return jsonify({
>         "error": "invalid_token",
>         "error_description": str(error)
>     }), 401, error.get_headers()
>
>
> @app.errorhandler(ApiError)
> def handle_api_error(error):
>     """Auth0 API エラー（ネットワーク、レート制限など）を処理"""
>     app.logger.error(f"Auth0 API error: {error.code} - {error.message}")
>     return jsonify({
>         "error": error.code,
>         "error_description": error.message
>     }), error.status_code or 500
>
>
> @app.errorhandler(Exception)
> def handle_generic_error(error):
>     """予期しないエラーをまとめて処理"""
>     app.logger.error(f"Unexpected error: {str(error)}", exc_info=True)
>     return jsonify({"error": "Internal server error"}), 500
> ```
>
> > [!NOTE]
> >
> > すべての認証エラーは `BaseAuthError` を継承しており、WWW-Authenticate ヘッダーを含む適切な HTTP レスポンスを返すために、`get_status_code()`、`get_headers()`、`get_error_code()` などのメソッドを提供します。

> [accordion] Before-Requestミドルウェアの使用
>
> ほとんどのエンドポイントで認証が必要なアプリケーションでは、Flask の `before_request` を使ってトークンをグローバルに検証します。
>
> ```python theme={null}
> from flask import g
>
> PUBLIC_ROUTES = ["/api/public", "/health"]
>
> @app.before_request
> async def verify_token():
>     # 公開ルートでは認証をスキップ
>     if request.path in PUBLIC_ROUTES:
>         return
>
>     auth_header = request.headers.get("Authorization", "")
>
>     if not auth_header.startswith("Bearer "):
>         return jsonify({"error": "Missing authorization"}), 401
>
>     token = auth_header.split(" ")[1]
>
>     try:
>         claims = await api_client.verify_access_token(token)
>         g.user_claims = claims
>     except BaseAuthError as e:
>         return jsonify({"error": str(e)}), e.get_status_code(), e.get_headers()
>
>
> @app.route("/api/protected-data")
> async def protected_data():
>     # クレームは g.user_claims から自動的に利用可能
>     return jsonify({"user_id": g.user_claims["sub"]})
> ```

## よくある問題

> [accordion] 401 未認可 - 無効な audience
>
> **症状**: 有効そうに見えるトークンを使っていても 401 エラーが発生する
>
> **原因**: トークン内の audience が、API クライアントに設定した audience と一致していない
>
> **解決策**:
>
> 1. `.env` ファイル内の `AUTH0_AUDIENCE` が Auth0 API 識別子 と完全に一致していることを確認する
> 2. audience では大文字と小文字が区別される
> 3. audience が URL または URN 形式になっていることを確認する (例: `my-api` ではなく `https://my-api`)

> [accordion] 401 未認可 - 無効な 発行者
>
> **症状**: 発行者が一致せず、トークンのバリデーションに失敗する
>
> **原因**: ドメインの設定がトークンの発行者と一致していない
>
> **解決策**:
>
> 1. `AUTH0_DOMAIN` が正しいことを確認する (例: `tenant.us.auth0.com`)
> 2. ドメインに `https://` を含めない
> 3. 末尾にスラッシュを付けない

> [accordion] 設定値が見つかりません
>
> **症状**: `None` の値や環境変数に関するエラーが発生する
>
> **原因**: 環境変数が読み込まれていない、または `.env` ファイルが見つからない
>
> **解決策**:
>
> 1. `.env` ファイルがプロジェクトのルートに存在することを確認する
> 2. `os.getenv()` を呼び出す前に `load_dotenv()` が実行されていることを確認する
> 3. 変数名が完全に一致していることを確認する (大文字と小文字を区別)

> [accordion] Flask の async サポートエラー
>
> **症状**: `RuntimeError: This event loop is already running` または同様の async エラーが発生する
>
> **原因**: Flask 3.0 以降を使わずに async のルートを使用している、または sync と async を不適切に混在させている
>
> **解決策**:
>
> 1. Flask 3.0 以上にアップグレードする: `pip install --upgrade flask`
> 2. `api_client` を使用するすべてのルートハンドラーが `async def` として宣言されていることを確認する
> 3. ルートハンドラー内で `asyncio.run()` を使用しない

> [accordion] トークンの有効期限切れエラー
>
> **症状**: `VerifyAccessTokenError: Token is expired`
>
> **原因**: アクセストークンの有効期限が切れている
>
> **解決策**:
>
> 1. Auth0 Dashboard の Test タブから新しいトークンをリクエストする
> 2. クライアントアプリケーションでトークンの更新を実装する
> 3. Auth0 Dashboard のトークンは通常 24 時間有効

> [accordion] `Authorization` ヘッダーがありません
>
> **症状**: `Missing or invalid authorization header` エラー
>
> **原因**: リクエストに `Authorization` ヘッダーが含まれていない、または形式が正しくない
>
> **解決策**:
>
> 1. ヘッダー名が `Authorization` (A は大文字) であることを確認する
> 2. 次の形式を使用する: `Authorization: Bearer YOUR_TOKEN`
> 3. トークンを引用符で囲まない

## 追加リソース

> [card] [SDKドキュメント](https://github.com/auth0/auth0-api-python)
>
> SDKの完全なドキュメントとAPIリファレンス

> [card] [Flaskドキュメント](https://flask.palletsprojects.com/)
>
> Flaskフレームワークの公式ドキュメント

> [card] [Auth0 Dashboard](https://manage.auth0.com/)
>
> Auth0 テナントとAPIを管理

> [card] [API認証ガイド](/docs/docs/ja-jp/secure/tokens/access-tokens)
>
> アクセストークンとAPIセキュリティについて詳しく見る

> [card] [DPoPドキュメント](/docs/docs/ja-jp/secure/sender-constraining/demonstrating-proof-of-possession-dpop)
>
> Proof-of-Possessionセキュリティについて詳しく見る

> [card] [コミュニティフォーラム](https://community.auth0.com/)
>
> Auth0 Communityでサポートを受ける

## 次のステップ

Flask を使った完全に動作するサンプルについては、[Auth0 Python API samples repository](https://github.com/auth0-samples/auth0-python-api-samples)をご覧ください。
