为 Cloud Functions 启用 App Check 强制执行

要开始在可调用的 Cloud Functions 中强制执行 App Check 令牌要求,请修改您的函数以检查有效的 App Check 令牌。

在你开始之前

启用应用程序检查你的苹果安卓网页客户端。

向函数添加 App Check 支持

  1. 更新项目的firebase-functions依赖于3.14.0或更新的版本:

    npm install firebase-functions@">=3.14.0"
    

    而更新项目的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. 如果你想用自己的逻辑来处理无效的应用程序检查令牌(可选)(例如,如果你想暂时登录,而不是拒绝,使全面执行前,无效请求),设置allowInvalidAppCheckTokentrue

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

    为了能够全面应用程序检查保护,设置allowInvalidAppCheckTokenfalse

  4. 重新部署您的功能:

    firebase deploy --only functions
    

部署这些更改后,您的可调用 Cloud Functions 将需要有效的 App Check 令牌。当您调用可调用函数时,Cloud Functions 客户端 SDK 会自动附加应用检查令牌。