當您了解 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 令牌。