了解 2023 年 Google I/O 大会上介绍的 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(预览版)

    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 令牌。