Firebase 将于 5 月 10 日重返 Google I/O 大会!立即报名

為 Cloud Functions 啟用應用檢查強制執行

當您了解 App Check 將如何影響您的用戶並準備好繼續操作時,您可以啟用 App Check 強制執行。

要開始在您的可調用 Cloud Functions 中執行 App Check 令牌要求,請修改您的函數以檢查有效的 App Check 令牌,如下所示。啟用強制執行後,所有未經驗證的請求都將被拒絕。

  1. 將項目的firebase-functions依賴項更新到版本 4.0.0 或更新版本:

    npm install firebase-functions@">=4.0.0"
    

    並將項目的firebase-admin依賴項更新到版本 9.8.0 或更高版本:

    npm install firebase-admin@">=9.8.0"
    
  2. 將函數的enforceAppCheck運行時選項設置為true

    exports.yourCallableFunction = functions.
      .runWith({
        enforceAppCheck: true  // Requests without valid App Check tokens will be rejected.
      })
      .https.onCall((data, context) => {
        // Your function logic follows.
      });
    
  3. 在您的函數中添加對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.
    });
    
  4. 重新部署您的功能:

    firebase deploy --only functions
    

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