当您了解 App Check 将如何影响您的用户并准备好继续操作时,您可以启用 App Check 强制执行。
要开始在您的可调用 Cloud Functions 中执行 App Check 令牌要求,请修改您的函数以检查有效的 App Check 令牌,如下所示。启用强制执行后,所有未经验证的请求都将被拒绝。
将项目的
firebase-functions
依赖项更新到版本 4.0.0 或更新版本:npm install firebase-functions@">=4.0.0"
并将项目的 firebase
firebase-admin
依赖项更新到版本 9.8.0 或更高版本:npm install firebase-admin@">=9.8.0"
将函数的
enforceAppCheck
运行时选项设置为true
:exports.yourCallableFunction = functions. .runWith({ enforceAppCheck: true // Requests without valid App Check tokens will be rejected. }) .https.onCall((data, context) => { // Your function logic follows. });
在您的函数中添加对
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. });
重新部署您的功能:
firebase deploy --only functions
部署这些更改后,您的可调用 Cloud Functions 将需要有效的 App Check 令牌。当您调用可调用函数时,Cloud Functions 客户端 SDK 会自动附加一个 App Check 令牌。