ในการเริ่มต้นบังคับใช้ข้อกำหนดโทเค็น App Check ใน Cloud Functions ที่เรียกได้ ให้แก้ไขฟังก์ชันของคุณเพื่อตรวจสอบโทเค็น App Check ที่ถูกต้อง
ก่อนจะเริ่ม
เปิดใช้งาน App Check ในไคลเอนต์ Apple , Android และ เว็บ ของคุณ
เพิ่ม App Check รองรับฟังก์ชั่น
อัปเดตการพึ่งพา
firebase-functions
firebase ของโปรเจ็กต์เป็นเวอร์ชัน 3.14.0 หรือใหม่กว่า:npm install firebase-functions@">=3.14.0"
และอัปเดตการพึ่งพา
firebase-admin
ของโปรเจ็กต์เป็นเวอร์ชัน 9.8.0 หรือใหม่กว่า:npm install firebase-admin@">=9.8.0"
เพิ่มการตรวจสอบ
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. });
(ไม่บังคับ) หากคุณต้องการจัดการโทเค็น 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. });
หากต้องการเปิดใช้งานการป้องกัน App Check แบบเต็ม ให้ตั้งค่า
allowInvalidAppCheckToken
false
ปรับใช้ฟังก์ชันของคุณใหม่:
firebase deploy --only functions
เมื่อปรับใช้การเปลี่ยนแปลงเหล่านี้แล้ว Cloud Functions ที่เรียกใช้ได้ของคุณจะต้องใช้โทเค็น App Check ที่ถูกต้อง SDK ไคลเอ็นต์ Cloud Functions จะแนบโทเค็น App Check โดยอัตโนมัติเมื่อคุณเรียกใช้ฟังก์ชันที่เรียกได้