Admin SDK की मदद से, एडमिन के खास अधिकारों या सीमित अधिकारों के साथ, रीयलटाइम डेटाबेस का डेटा पढ़ा और लिखा जा सकता है. इस दस्तावेज़ में, हम आपको Firebase Realtime Database को ऐक्सेस करने के लिए, अपने प्रोजेक्ट में Firebase Admin SDK टूल जोड़ने का तरीका बताएंगे.
Admin SDK सेटअप
अपने सर्वर पर Firebase रीयलटाइम डेटाबेस का इस्तेमाल शुरू करने के लिए, आपको सबसे पहले अपनी पसंद की भाषा में Firebase Admin SDK सेट अप करना होगा.
Admin SDK की मदद से पुष्टि करना
Firebase Admin SDK का इस्तेमाल करके, किसी सर्वर से Firebase Realtime Database को ऐक्सेस करने से पहले, आपको Firebase के साथ अपने सर्वर की पुष्टि करनी होगी. किसी सर्वर की पुष्टि करते समय, उपयोगकर्ता खाते के क्रेडेंशियल से साइन इन करने के बजाय, सेवा खाते से पुष्टि की जाती है. इससे Firebase को आपके सर्वर की पहचान करने में मदद मिलती है.
Firebase Admin SDK का इस्तेमाल करके पुष्टि करने पर, आपको दो अलग-अलग लेवल का ऐक्सेस मिल सकता है:
| Firebase Admin SDK के लिए, पुष्टिकरण के ऐक्सेस लेवल | |
|---|---|
| एडमिन के अधिकार | किसी प्रोजेक्ट के Realtime Database को पढ़ने और उसमें बदलाव करने का पूरा ऐक्सेस. इस भूमिका का इस्तेमाल सावधानी से करें. इसका इस्तेमाल, डेटा माइग्रेशन या रीस्ट्रक्चरिंग जैसे एडमिन से जुड़े टास्क पूरे करने के लिए करें. इन टास्क के लिए, आपके प्रोजेक्ट के संसाधनों का पूरा ऐक्सेस होना ज़रूरी है. |
| सीमित सुविधाएं | प्रोजेक्ट के Realtime Database का ऐक्सेस, जो सिर्फ़ उन संसाधनों तक सीमित है जिनकी ज़रूरत आपके सर्वर को है. इस लेवल का इस्तेमाल, एडमिन से जुड़े ऐसे टास्क पूरे करने के लिए करें जिनके लिए ऐक्सेस की ज़रूरी शर्तें साफ़ तौर पर तय की गई हैं. उदाहरण के लिए, पूरे डेटाबेस में डेटा को पढ़ने वाले किसी समराइज़ेशन जॉब को चलाते समय, गलती से डेटा लिखने से बचा जा सकता है. इसके लिए, सिर्फ़ पढ़ने के लिए सुरक्षा नियम सेट करें. इसके बाद, उस नियम के तहत सीमित अधिकारों के साथ Admin SDK टूल को शुरू करें. |
एडमिन के खास अधिकारों से पुष्टि करना
जब Firebase Admin SDK को किसी ऐसे सेवा खाते के क्रेडेंशियल के साथ शुरू किया जाता है जिसके पास आपके Firebase प्रोजेक्ट में एडिटर की भूमिका होती है, तो उस इंस्टेंस के पास आपके प्रोजेक्ट के Realtime Database को पढ़ने और उसमें बदलाव करने का पूरा ऐक्सेस होता है.
Java
// Initialize the SDK with Application Default Credentials FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) // 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
import { initializeApp } from 'firebase-admin/app'; import { getDatabase } from 'firebase-admin/database'; // Initialize the app with Application Default Credentials, granting admin privileges initializeApp({ // 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 const db = getDatabase(); const ref = db.ref("restricted_access/secret_document"); ref.once("value", (snapshot) => { console.log(snapshot.val()); });
Python
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())
जाएं
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)
सीमित अधिकारों के साथ पुष्टि करना
सबसे सही तरीका यह है कि किसी सेवा के पास सिर्फ़ उन संसाधनों का ऐक्सेस होना चाहिए जिनकी उसे ज़रूरत है. Firebase ऐप्लिकेशन इंस्टेंस जिन संसाधनों को ऐक्सेस कर सकता है उन पर ज़्यादा बेहतर कंट्रोल पाने के लिए, अपनी सेवा को दिखाने के लिए सुरक्षा नियमों में यूनीक आइडेंटिफ़ायर का इस्तेमाल करें. इसके बाद, सही नियम सेट अप करें, ताकि आपकी सेवा को ज़रूरी संसाधनों का ऐक्सेस मिल सके. उदाहरण के लिए:
{
"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'"
}
}
}
इसके बाद, अपने सर्वर पर Firebase ऐप्लिकेशन को शुरू करते समय, databaseAuthVariableOverride विकल्प का इस्तेमाल करें. इससे, आपके डेटाबेस के नियमों में इस्तेमाल किए गए auth ऑब्जेक्ट को बदला जा सकेगा. इस कस्टम auth ऑब्जेक्ट में, uid फ़ील्ड को उस आइडेंटिफ़ायर पर सेट करें जिसका इस्तेमाल आपने सुरक्षा के नियमों में अपनी सेवा को दिखाने के लिए किया था.
Java
// 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 = FirebaseOptions.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) // 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
import { initializeApp } from 'firebase-admin/app'; import { getDatabase } from 'firebase-admin/database'; // Initialize the app with a custom auth variable, limiting the server's access initializeApp({ // 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 const db = getDatabase(); const ref = db.ref("/some_resource"); ref.once("value", (snapshot) => { console.log(snapshot.val()); });
Python
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())
जाएं
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)
कुछ मामलों में, हो सकता है कि आप Admin SDK टूल को डाउनस्कोप करना चाहें, ताकि वह बिना पुष्टि वाले क्लाइंट के तौर पर काम कर सके. डेटाबेस ऑथराइज़ेशन वैरिएबल को बदलने के लिए, null की वैल्यू देकर ऐसा किया जा सकता है.
Java
// Initialize the app with Application Default Credentials FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) // 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
import { initializeApp } from 'firebase-admin/app'; import { getDatabase } from 'firebase-admin/database'; // Initialize the app with a null auth variable, limiting the server's access initializeApp({ // 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 const db = getDatabase(); const ref = db.ref("/public_resource"); ref.once("value", (snapshot) => { console.log(snapshot.val()); });
Python
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())
जाएं
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)
अगले चरण
- Realtime Database के लिए डेटा को स्ट्रक्चर करने का तरीका जानें.
- डेटा को कई डेटाबेस इंस्टेंस में स्केल करना.
- डेटा सेव करें.
- डेटा वापस पाना.
- Firebase कंसोल में अपना डेटाबेस देखें.