Join us in person and online for Firebase Summit on October 18, 2022. Learn how Firebase can help you accelerate app development, release your app with confidence, and scale with ease. Register now

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

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

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

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

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

    npm install firebase-functions@">=3.14.0"
    

    並將項目的 firebase 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. (可選)如果您想使用自己的邏輯處理無效的 App Check 令牌(例如,如果您想在啟用完全強制之前暫時記錄而不是拒絕無效請求),請將allowInvalidAppCheckToken設置為true

    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.
      });
    

    要啟用完整的應用檢查保護,請將allowInvalidAppCheckToken設置為false

  4. 重新部署您的功能:

    firebase deploy --only functions
    

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