Google I/O 2023 での Firebase の最新情報。詳細

Cloud Functions の関数で App Check の適用を有効にする

App Check がユーザーに与える影響を理解し、続行する準備ができたら、App Check の適用を有効にできます。

呼び出し可能な Cloud Functions の関数で App Check トークンを必須にするには、以下に示すように、有効な App Check トークンを確認するように関数を変更します。適用を有効にすると、未検証のリクエストはすべて拒否されます。

  1. Cloud Functions SDK をインストールします。

    Node.js(第 1 世代)

    プロジェクトの firebase-functions 依存関係をバージョン 4.0.0 以降に更新します。

    npm install firebase-functions@">=4.0.0"
    

    Node.js(第 2 世代)

    プロジェクトの firebase-functions 依存関係をバージョン 4.0.0 以降に更新します。

    npm install firebase-functions@">=4.0.0"
    

    Python(プレビュー)

    functions/requirements.txtfirebase-functions を追加します。

    firebase-functions >= 0.1.0
    

    次に、プロジェクトの仮想環境の依存関係を更新します。

    ./venv/bin/pip install -r requirements.txt
    
  2. 関数の App Check 適用ランタイム オプションを有効にします。

    Node.js(第 1 世代)

    const functions = require("firebase-functions/v1");
    
    exports.yourV1CallableFunction = functions
      .runWith({
          enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
      })
      .https.onCall((data, context) => {
            // context.app contains data from App Check, including the app ID.
            // Your function logic follows.
            ...
      });
    

    Node.js(第 2 世代)

    const { onCall } = require("firebase-functions/v2/https");
    
    exports.yourV2CallableFunction = onCall(
      {
        enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
      },
      (request) => {
        // request.app contains data from App Check, including the app ID.
        // Your function logic follows.
        ...
      }
    );
    

    Python(プレビュー)

    from firebase_functions import https_fn
    
    @https_fn.on_call(
        enforce_app_check=True  # Reject requests with missing or invalid App Check tokens.
    )
    def your_callable_function(req: https_fn.CallableRequest) -> https_fn.Response:
        # req.app contains data from App Check, including the app ID.
        # Your function logic follows.
        ...
    
  3. 関数を再デプロイします。

    firebase deploy --only functions
    

これらの変更がデプロイされると、呼び出し可能な Cloud Functions の関数で有効な App Check トークンが必須になります。呼び出し可能関数を呼び出すと、Cloud Functions クライアントの SDK が App Check トークンを自動的に追加します。