Dengan Admin SDK, Anda dapat membaca dan menulis data Realtime Database dengan hak istimewa admin penuh, atau dengan hak istimewa terbatas yang lebih mendetail. Dalam dokumen ini, kami akan memandu Anda menambahkan Firebase Admin SDK ke proyek Anda untuk mengakses Firebase Realtime Database.
Penyiapan SDK Admin
Untuk memulai Firebase Realtime Database di server, pertama-tama Anda harus menyiapkan Firebase Admin SDK dalam bahasa pilihan Anda.
Autentikasi Admin SDK
Sebelum Anda dapat mengakses Firebase Realtime Database dari server menggunakan Firebase Admin SDK, Anda harus mengautentikasi server Anda dengan Firebase. Saat Anda mengautentikasi server, alih-alih masuk dengan kredensial akun pengguna seperti yang Anda lakukan di aplikasi klien, Anda mengautentikasi dengan akun layanan yang mengidentifikasi server Anda ke Firebase.
Anda bisa mendapatkan dua tingkat akses yang berbeda saat mengautentikasi menggunakan Firebase Admin SDK:
Tingkat Akses Autentikasi Firebase Admin SDK | |
---|---|
Hak istimewa administratif | Menyelesaikan akses baca dan tulis ke Realtime Database proyek. Gunakan dengan hati-hati untuk menyelesaikan tugas administratif seperti migrasi atau restrukturisasi data yang memerlukan akses tak terbatas ke sumber daya proyek Anda. |
Hak istimewa terbatas | Akses ke Realtime Database proyek, terbatas hanya pada sumber daya yang dibutuhkan server Anda. Gunakan level ini untuk menyelesaikan tugas administratif yang memiliki persyaratan akses yang jelas. Misalnya, saat menjalankan tugas peringkasan yang membaca data di seluruh database, Anda dapat melindungi dari penulisan yang tidak disengaja dengan menyetel aturan keamanan hanya baca, lalu menginisialisasi Admin SDK dengan hak istimewa yang dibatasi oleh aturan tersebut. |
Autentikasi dengan hak istimewa admin
Saat Anda menginisialisasi Firebase Admin SDK dengan kredensial untuk akun layanan dengan peran Editor di project Firebase Anda, instance tersebut memiliki akses baca dan tulis lengkap ke Realtime Database project Anda.
Jawa
// Fetch the service account key JSON file contents FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json"); // Initialize the app with a service account, granting admin privileges FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) // The database URL depends on the location of the database .setDatabaseUrl("https://DATABASE_NAME.firebaseio.com") .build(); FirebaseApp.initializeApp(options); // As an admin, the app has access to read and write all data, regardless of Security Rules DatabaseReference ref = FirebaseDatabase.getInstance() .getReference("restricted_access/secret_document"); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Object document = dataSnapshot.getValue(); System.out.println(document); } @Override public void onCancelled(DatabaseError error) { } });
Node.js
var admin = require("firebase-admin"); // Fetch the service account key JSON file contents var serviceAccount = require("path/to/serviceAccountKey.json"); // Initialize the app with a service account, granting admin privileges admin.initializeApp({ credential: admin.credential.cert(serviceAccount), // The database URL depends on the location of the database databaseURL: "https://DATABASE_NAME.firebaseio.com" }); // As an admin, the app has access to read and write all data, regardless of Security Rules var db = admin.database(); var ref = db.ref("restricted_access/secret_document"); ref.once("value", function(snapshot) { console.log(snapshot.val()); });
Piton
import firebase_admin from firebase_admin import credentials from firebase_admin import db # Fetch the service account key JSON file contents cred = credentials.Certificate('path/to/serviceAccountKey.json') # Initialize the app with a service account, granting admin privileges firebase_admin.initialize_app(cred, { 'databaseURL': 'https://databaseName.firebaseio.com' }) # As an admin, the app has access to read and write all data, regradless of Security Rules ref = db.reference('restricted_access/secret_document') print(ref.get())
Pergi
ctx := context.Background() conf := &firebase.Config{ DatabaseURL: "https://databaseName.firebaseio.com", } // Fetch the service account key JSON file contents opt := option.WithCredentialsFile("path/to/serviceAccountKey.json") // Initialize the app with a service account, granting admin privileges app, err := firebase.NewApp(ctx, conf, opt) if err != nil { log.Fatalln("Error initializing app:", err) } client, err := app.Database(ctx) if err != nil { log.Fatalln("Error initializing database client:", err) } // As an admin, the app has access to read and write all data, regradless of Security Rules ref := client.NewRef("restricted_access/secret_document") var data map[string]interface{} if err := ref.Get(ctx, &data); err != nil { log.Fatalln("Error reading from database:", err) } fmt.Println(data)
Otentikasi dengan hak istimewa terbatas
Sebagai praktik terbaik, layanan harus memiliki akses hanya ke sumber daya yang dibutuhkannya. Untuk mendapatkan kontrol yang lebih mendetail atas sumber daya yang dapat diakses instance aplikasi Firebase, gunakan pengidentifikasi unik di Aturan Keamanan untuk mewakili layanan Anda. Kemudian atur aturan yang sesuai yang memberikan layanan Anda akses ke sumber daya yang dibutuhkannya. Sebagai contoh:
{ "rules": { "public_resource": { ".read": true, ".write": true }, "some_resource": { ".read": "auth.uid === 'my-service-worker'", ".write": false }, "another_resource": { ".read": "auth.uid === 'my-service-worker'", ".write": "auth.uid === 'my-service-worker'" } } }
Kemudian, di server Anda, saat menginisialisasi aplikasi Firebase, gunakan opsi databaseAuthVariableOverride
untuk mengganti objek auth
yang digunakan oleh aturan database Anda. Di objek auth
khusus ini, setel bidang uid
ke pengidentifikasi yang Anda gunakan untuk mewakili layanan Anda di Aturan Keamanan Anda.
Jawa
// Fetch the service account key JSON file contents FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json"); // Initialize the app with a custom auth variable, limiting the server's access Map<String, Object> auth = new HashMap<String, Object>(); auth.put("uid", "my-service-worker"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(serviceAccount)) // The database URL depends on the location of the database .setDatabaseUrl("https://DATABASE_NAME.firebaseio.com") .setDatabaseAuthVariableOverride(auth) .build(); FirebaseApp.initializeApp(options); // The app only has access as defined in the Security Rules DatabaseReference ref = FirebaseDatabase .getInstance() .getReference("/some_resource"); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String res = dataSnapshot.getValue(); System.out.println(res); } });
Node.js
var admin = require("firebase-admin"); // Fetch the service account key JSON file contents var serviceAccount = require("path/to/serviceAccountKey.json"); // Initialize the app with a custom auth variable, limiting the server's access admin.initializeApp({ credential: admin.credential.cert(serviceAccount), // The database URL depends on the location of the database databaseURL: "https://DATABASE_NAME.firebaseio.com", databaseAuthVariableOverride: { uid: "my-service-worker" } }); // The app only has access as defined in the Security Rules var db = admin.database(); var ref = db.ref("/some_resource"); ref.once("value", function(snapshot) { console.log(snapshot.val()); });
Piton
import firebase_admin from firebase_admin import credentials from firebase_admin import db # Fetch the service account key JSON file contents cred = credentials.Certificate('path/to/serviceAccountKey.json') # Initialize the app with a custom auth variable, limiting the server's access firebase_admin.initialize_app(cred, { 'databaseURL': 'https://databaseName.firebaseio.com', 'databaseAuthVariableOverride': { 'uid': 'my-service-worker' } }) # The app only has access as defined in the Security Rules ref = db.reference('/some_resource') print(ref.get())
Pergi
ctx := context.Background() // Initialize the app with a custom auth variable, limiting the server's access ao := map[string]interface{}{"uid": "my-service-worker"} conf := &firebase.Config{ DatabaseURL: "https://databaseName.firebaseio.com", AuthOverride: &ao, } // Fetch the service account key JSON file contents opt := option.WithCredentialsFile("path/to/serviceAccountKey.json") app, err := firebase.NewApp(ctx, conf, opt) if err != nil { log.Fatalln("Error initializing app:", err) } client, err := app.Database(ctx) if err != nil { log.Fatalln("Error initializing database client:", err) } // The app only has access as defined in the Security Rules ref := client.NewRef("/some_resource") var data map[string]interface{} if err := ref.Get(ctx, &data); err != nil { log.Fatalln("Error reading from database:", err) } fmt.Println(data)
Dalam beberapa kasus, Anda mungkin ingin menurunkan cakupan Admin SDK untuk bertindak sebagai klien yang tidak diautentikasi. Anda dapat melakukan ini dengan memberikan nilai null
untuk penggantian variabel autentikasi basis data.
Jawa
// Fetch the service account key JSON file contents FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(serviceAccount)) // The database URL depends on the location of the database .setDatabaseUrl("https://DATABASE_NAME.firebaseio.com") .setDatabaseAuthVariableOverride(null) .build(); FirebaseApp.initializeApp(options); // The app only has access to public data as defined in the Security Rules DatabaseReference ref = FirebaseDatabase .getInstance() .getReference("/public_resource"); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String res = dataSnapshot.getValue(); System.out.println(res); } });
Node.js
var admin = require("firebase-admin"); // Fetch the service account key JSON file contents var serviceAccount = require("path/to/serviceAccountKey.json"); // Initialize the app with a null auth variable, limiting the server's access admin.initializeApp({ credential: admin.credential.cert(serviceAccount), // The database URL depends on the location of the database databaseURL: "https://DATABASE_NAME.firebaseio.com", databaseAuthVariableOverride: null }); // The app only has access to public data as defined in the Security Rules var db = admin.database(); var ref = db.ref("/public_resource"); ref.once("value", function(snapshot) { console.log(snapshot.val()); });
Piton
import firebase_admin from firebase_admin import credentials from firebase_admin import db # Fetch the service account key JSON file contents cred = credentials.Certificate('path/to/serviceAccountKey.json') # Initialize the app with a None auth variable, limiting the server's access firebase_admin.initialize_app(cred, { 'databaseURL': 'https://databaseName.firebaseio.com', 'databaseAuthVariableOverride': None }) # The app only has access to public data as defined in the Security Rules ref = db.reference('/public_resource') print(ref.get())
Pergi
ctx := context.Background() // Initialize the app with a nil auth variable, limiting the server's access var nilMap map[string]interface{} conf := &firebase.Config{ DatabaseURL: "https://databaseName.firebaseio.com", AuthOverride: &nilMap, } // Fetch the service account key JSON file contents opt := option.WithCredentialsFile("path/to/serviceAccountKey.json") app, err := firebase.NewApp(ctx, conf, opt) if err != nil { log.Fatalln("Error initializing app:", err) } client, err := app.Database(ctx) if err != nil { log.Fatalln("Error initializing database client:", err) } // The app only has access to public data as defined in the Security Rules ref := client.NewRef("/some_resource") var data map[string]interface{} if err := ref.Get(ctx, &data); err != nil { log.Fatalln("Error reading from database:", err) } fmt.Println(data)
Langkah selanjutnya
- Pelajari cara menyusun data untuk Realtime Database.
- Menskalakan data di beberapa instans basis data .
- Hemat kuota.
- Ambil data.
- Lihat database Anda di konsol Firebase.