ข้อมูลเบื้องต้นเกี่ยวกับ Admin Database SDK

Admin SDK ช่วยให้คุณอ่านและเขียนข้อมูล Realtime Database ได้ด้วยสิทธิ์ของผู้ดูแลระบบแบบเต็ม หรือสิทธิ์แบบจำกัดที่ละเอียดกว่า ในเอกสารนี้ เราจะแนะนำขั้นตอนการเพิ่ม Firebase Admin SDK ลงในโปรเจ็กต์เพื่อเข้าถึง Firebase Realtime Database

การตั้งค่า Admin SDK

หากต้องการเริ่มต้นใช้งานฐานข้อมูลเรียลไทม์ของ Firebase ในเซิร์ฟเวอร์ คุณจะต้อง ตั้งค่า Firebase Admin SDK ในภาษาที่ต้องการก่อน

การตรวจสอบสิทธิ์ Admin SDK

คุณต้อง ตรวจสอบสิทธิ์เซิร์ฟเวอร์กับ Firebase ก่อนจึงจะเข้าถึง Firebase Realtime Database จากเซิร์ฟเวอร์โดยใช้ Firebase Admin SDK ได้ เมื่อตรวจสอบสิทธิ์เซิร์ฟเวอร์ คุณจะตรวจสอบสิทธิ์ด้วย บัญชีบริการ ซึ่งระบุเซิร์ฟเวอร์ของคุณกับ Firebase แทนการลงชื่อเข้าใช้ด้วยข้อมูลเข้าสู่ระบบของบัญชีผู้ใช้เหมือนในแอปไคลเอ็นต์

คุณจะได้รับสิทธิ์เข้าถึง 2 ระดับที่แตกต่างกันเมื่อตรวจสอบสิทธิ์โดยใช้ 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())
Go
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())
Go
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())
Go
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)

ขั้นตอนถัดไป