為 Cloud Functions 啟用 App Check 強制執行

要開始在可調用的 Cloud Functions 中強制執行 App Check 令牌要求,請修改您的函數以檢查有效的 App Check 令牌。

在你開始之前

啟用應用程序檢查你的蘋果安卓網頁客戶端。

向函數添加 App Check 支持

  1. 更新項目的firebase-functions依賴於3.14.0或更新的版本:

    npm install firebase-functions@">=3.14.0"
    

    而更新項目的firebase-admin依賴於9.8.0或更新的版本:

    npm install firebase-admin@">=9.8.0"
    
  2. 一檢查添加context.app給你的函數。如果你的函數會失敗context.app沒有定義。

    exports.yourCallableFunction = functions.https.onCall((data, context) => {
      // context.app will be undefined if the request doesn't include an
      // App Check token. (If the request includes an invalid App Check
      // token, the request will be rejected with HTTP error 401.)
      if (context.app == undefined) {
        throw new functions.https.HttpsError(
            'failed-precondition',
            'The function must be called from an App Check verified app.')
      }
    
      // Your function logic follows.
    });
    
  3. 如果你想用自己的邏輯來處理無效的應用程序檢查令牌(可選)(例如,如果你想暫時登錄,而不是拒絕,使全面執行前,無效請求),設置allowInvalidAppCheckTokentrue

    exports.yourCallableFunction = functions.
      .runWith({
        allowInvalidAppCheckToken: true  // Opt-out: Requests with invalid App
                                         // Check tokens continue to your code.
      })
      .https.onCall((data, context) => {
        // Now, requests with an invalid App Check token are not rejected.
        //
        // context.app will be undefined if the request:
        //   1) Does not include an App Check token
        //   2) Includes an invalid App Check token
        if (context.app == undefined) {
          // You can inspect the raw request header to check whether an App
          // Check token was provided in the request. If you're not ready to
          // fully enable App Check yet, you could log these conditions instead
          // of throwing errors.
          const rawToken = context.rawRequest.header['X-Firebase-AppCheck'];
          if (rawToken == undefined) {
            throw new functions.https.HttpsError(
                'failed-precondition',
                'The function must be called from an App Check verified app.'
            );
          } else {
            throw new functions.https.HttpsError(
                'unauthenticated',
                'Provided App Check token failed to validate.'
            );
          }
        }
    
        // Your function logic follows.
      });
    

    為了能夠全面應用程序檢查保護,設置allowInvalidAppCheckTokenfalse

  4. 重新部署您的功能:

    firebase deploy --only functions
    

部署這些更改後,您的可調用 Cloud Functions 將需要有效的 App Check 令牌。當您調用可調用函數時,Cloud Functions 客戶端 SDK 會自動附加應用檢查令牌。