欢迎参加我们将于 2022 年 10 月 18 日举办的 Firebase 峰会(线上线下同时进行),了解 Firebase 如何帮助您加快应用开发速度、满怀信心地发布应用并在之后需要时轻松地扩大应用规模。立即报名

为 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 会自动附加应用检查令牌。