Untuk mulai menerapkan persyaratan token App Check di Cloud Functions Anda yang dapat dipanggil, ubah fungsi Anda untuk memeriksa token App Check yang valid.
Sebelum kamu memulai
Aktifkan App Check di klien Apple , Android , dan Web Anda.
Tambahkan dukungan App Check ke suatu fungsi
Perbarui ketergantungan
firebase-functions
proyek Anda ke versi 3.14.0 atau yang lebih baru:npm install firebase-functions@">=3.14.0"
Dan perbarui ketergantungan
firebase-admin
proyek Anda ke versi 9.8.0 atau yang lebih baru:npm install firebase-admin@">=9.8.0"
Tambahkan tanda centang untuk
context.app
ke fungsi Anda. Fungsi Anda akan gagal jikacontext.app
tidak ditentukan.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. });
(Opsional) Jika Anda ingin menangani token App Check yang tidak valid dengan logika Anda sendiri (misalnya, jika Anda ingin log sementara, daripada menolak, permintaan yang tidak valid sebelum mengaktifkan penegakan penuh), setel
allowInvalidAppCheckToken
ketrue
: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. });
Untuk mengaktifkan perlindungan App Check penuh, setel
allowInvalidAppCheckToken
kefalse
.Terapkan kembali fungsi Anda:
firebase deploy --only functions
Setelah perubahan ini diterapkan, Cloud Functions Anda yang dapat dipanggil akan memerlukan token App Check yang valid. SDK klien Cloud Functions secara otomatis melampirkan token App Check saat Anda menjalankan fungsi yang dapat dipanggil.