為 Cloud Functions 啟用 App Check 強制執行功能

瞭解App Check 對使用者的影響後, 準備就緒後,您可以啟用「App Check」強制執行功能。

啟用強制執行機制

開始在可呼叫中執行 App Check 權杖要求 Cloud Functions,修改函式,檢查有效的 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 (預先發布版)

    firebase-functions 新增至 functions/requirements.txt

    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 權杖。

重播防護措施 (Beta 版)

如要防止可呼叫函式受到重送攻擊,您可使用應用程式 驗證權杖後,請檢查權杖。權杖使用完畢後,就無法再次使用。

請注意,使用重播保護功能會在符記驗證時增加網路往返傳送時間,因此會增加雲端函式呼叫的延遲時間。因此,大多數應用程式通常只會在特別敏感的端點啟用重播保護功能。

如要使用權杖,請按照下列指示操作:

  1. Cloud 控制台 授予「Firebase App Check 權杖驗證者」授予服務帳戶的角色 由 Cloud 函式使用

    • 如果您明確初始化 Admin SDK,並指定專案的 Admin SDK 服務帳戶憑證,系統就會授予必要的角色。
    • 如果您使用第 1 代 Cloud Functions 搭配預設的 Admin SDK 設定,請將角色授予 App Engine 預設服務帳戶。請參閱變更服務帳戶權限
    • 如果您使用第 2 代 Cloud Functions 搭配預設的 Admin SDK 設定,請將角色授予預設運算服務帳戶
  2. 將函式定義中的 consumeAppCheckToken 設為 true

    Node.js (第 1 代)

    const functions = require("firebase-functions/v1");
    
    exports.yourV1CallableFunction = functions
      .runWith({
          enforceAppCheck: true, // Reject requests with missing or invalid App Check tokens.
          consumeAppCheckToken: true  // Consume the token after verification.
      })
      .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.
        consumeAppCheckToken: true  // Consume the token after verification.
      },
      (request) => {
        // request.app contains data from App Check, including the app ID.
        // Your function logic follows.
        ...
      }
    );
    
  3. 更新應用程式用戶端程式碼,取得消耗性使用限制 符記:

    Swift

    let options = HTTPSCallableOptions(requireLimitedUseAppCheckTokens: true)
    let yourCallableFunction =
        Functions.functions().httpsCallable("yourCallableFunction", options: options)
    do {
        let result = try await yourCallableFunction.call()
    } catch {
        // ...
    }
    

    Web

    import { getFunctions, httpsCallable } from "firebase/functions";
    
    const yourCallableFunction = httpsCallable(
      getFunctions(),
      "yourCallableFunction",
      { limitedUseAppCheckTokens: true },
    );
    await yourCallableFunction();
    

    Kotlin+KTX

    val yourCallableFunction = Firebase.functions.getHttpsCallable("yourCallableFunction") {
        limitedUseAppCheckTokens = true
    }
    val result = yourCallableFunction.call().await()
    

    Java

    HttpsCallableReference yourCallableFunction = FirebaseFunctions.getInstance().getHttpsCallable(
            "yourCallableFunction",
            new HttpsCallableOptions.Builder()
                    .setLimitedUseAppCheckTokens(true)
                    .build()
    );
    Task<HttpsCallableResult> result = yourCallableFunction.call();