在了解 App Check 对用户有何影响并为后续操作做好准备之后,您便可以启用 App Check 强制执行。
如需开始在可调用的 Cloud Functions 函数中强制执行 App Check 令牌要求,请修改函数以检查是否具有有效的 App Check 令牌,如下所示。启用强制执行后,所有未经验证的请求都将被拒绝。
将项目的
firebase-functions
依赖项更新为 4.0.0 或更高版本:npm install firebase-functions@">=4.0.0"
将项目的
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 令牌。