將 Firebase Admin SDK 新增至伺服器

Admin SDK 是一組伺服器程式庫,可讓您在特權環境中與 Firebase 互動,執行下列動作:

  • 針對 Firebase Data Connect 服務執行查詢和變異,以便執行大量資料管理和其他操作,並具備完整的管理員權限。
  • 使用完整的管理員權限讀取及寫入 Realtime Database 資料。
  • 使用 Firebase Cloud Messaging 伺服器通訊協定的簡單替代方法,以程式設計方式傳送 Firebase Cloud Messaging 訊息。
  • 產生及驗證 Firebase 驗證權杖。
  • 存取與 Firebase 專案相關聯的 Google Cloud 資源,例如 Cloud Storage 值區和 Cloud Firestore 資料庫。
  • 您可以建立自己的簡易版管理控制台,用於查詢使用者資料或變更使用者的電子郵件地址以進行驗證等操作。

如果您想使用 Node.js SDK 做為用於最終使用者存取權的用戶端 (例如在 Node.js 桌面或 IoT 應用程式中),而非從特權環境 (例如伺服器) 存取管理員存取權,則應改為按照設定用戶端 JavaScript SDK 的操作說明操作。

以下是功能矩陣,顯示各語言支援的 Firebase 功能:

如要進一步瞭解這些用途的 Admin SDK 整合作業,請參閱對應的 Realtime DatabaseFCMAuthenticationRemote ConfigCloud Storage 說明文件。本頁其餘部分將著重於 Admin SDK 的基本設定。

事前準備

  • 確認您有伺服器應用程式。

  • 請根據您使用的 Admin SDK 執行下列操作:

    • Admin Node.js SDK - Node.js 18 以上版本
    • Admin Java SDK - Java 8 以上
    • 管理員 Python SDK:Python 3.7 以上版本 (建議使用 Python 3.8 以上版本)
      Python 3.7 支援已淘汰。
    • Admin Go SDK:Go 1.21 以上版本
    • Admin .NET SDK:.NET Framework 4.6.2 以上版本,或 .NET 6.0 以上版本的 .NET Standard 2.0

設定 Firebase 專案和服務帳戶

如要使用 Firebase Admin SDK,您需要:

  • Firebase 專案。
  • Firebase Admin SDK 服務帳戶,用於與 Firebase 通訊。建立 Firebase 專案或將 Firebase 新增至 Google Cloud 專案時,系統會自動建立這個服務帳戶。
  • 包含服務帳戶憑證的設定檔案。

如果您還沒有 Firebase 專案,請前往 Firebase 控制台建立專案。請參閱「瞭解 Firebase 專案」一文,進一步瞭解 Firebase 專案。

  1. Firebase 控制台中,按一下「新增專案」

    • 如要將 Firebase 資源新增至現有 Google Cloud 專案,請輸入專案名稱,或從下拉式選單中選取。

    • 如要建立新專案,請輸入所需的專案名稱。您也可以視需要編輯專案名稱下方顯示的專案 ID。

  2. 系統提示時,請詳閱並接受 Firebase 條款

  3. 按一下「繼續」

  4. (選用) 為專案設定 Google Analytics,即可在使用下列任何 Firebase 產品時,獲得最佳體驗:

    選取現有的 Google Analytics 帳戶,或建立新帳戶。

    如果您建立新帳戶,請選取Analytics報表位置,然後接受專案的資料共用設定和 Google Analytics 條款。

  5. 按一下「建立專案」 (如果您使用的是現有的 Google Cloud 專案,請按一下「新增 Firebase」)。

Firebase 會自動為 Firebase 專案佈建資源。程序完成後,您會前往 Firebase 主控台的 Firebase 專案總覽頁面。

新增 SDK

如果您要設定新專案,請為所選語言安裝 SDK。

Node.jsJavaPythonGoC#

Firebase Admin Node.js SDK 可在 npm 上取得。如果您尚未建立 package.json 檔案,請透過 npm init 建立一個。接著,請安裝 firebase-admin npm 套件,並將其儲存至 package.json

npm install firebase-admin --save

如要在應用程式中使用模組,請從任何 JavaScript 檔案中 require 模組:

const { initializeApp } = require('firebase-admin/app');

如果您使用的是 ES2015,可以 import 模組:

import { initializeApp } from 'firebase-admin/app';

Firebase Admin Java SDK 已發布至 Maven 中央存放區。如要安裝程式庫,請在 build.gradle 檔案中宣告該程式庫為依附元件:

dependencies {
  implementation 'com.google.firebase:firebase-admin:9.4.3'
}

如果您使用 Maven 建構應用程式,可以將下列依附元件新增至 pom.xml

<dependency>
  <groupId>com.google.firebase</groupId>
  <artifactId>firebase-admin</artifactId>
  <version>9.4.3</version>
</dependency>

您可以透過 pip 安裝 Firebase Admin Python SDK。您可以透過 sudo 為所有使用者安裝程式庫:

sudo pip install firebase-admin

或者,您也可以傳遞 --user 標記,只為目前使用者安裝程式庫:

pip install --user firebase-admin

您可以使用 go get 公用程式安裝 Go Admin SDK

# Install the latest version:
go get firebase.google.com/go/v4@latest

# Or install a specific version:
go get firebase.google.com/go/v4@4.15.2

您可以使用 .NET 套件管理工具安裝 .NET Admin SDK

Install-Package FirebaseAdmin -Version 3.1.0

或者,您也可以使用 dotnet 指令列公用程式安裝:

dotnet add package FirebaseAdmin --version 3.1.0

或者,您也可以在 .csproj 檔案中新增下列套件參照項目,以便安裝:

<ItemGroup>
  <PackageReference Include="FirebaseAdmin" Version="3.1.0" />
</ItemGroup>

初始化 SDK

建立 Firebase 專案後,您可以使用 Google 應用程式預設憑證初始化 SDK。由於在 Google 環境中,預設憑證查詢作業會完全自動化,因此不需要提供環境變數或其他設定,因此強烈建議在 Google 環境 (例如 Cloud Run、App Engine 和 Cloud Functions) 中執行的應用程式,採用這種方式初始化 SDK。

如要選擇為 Realtime DatabaseCloud StorageCloud Functions 等服務指定初始化選項,請使用 FIREBASE_CONFIG 環境變數。如果 FIREBASE_CONFIG 變數的內容以 { 開頭,系統會將其剖析為 JSON 物件。否則,SDK 會假設字串是包含選項的 JSON 檔案路徑。

Node.jsJavaPythonGoC#
const app = initializeApp();
FirebaseApp.initializeApp();
default_app = firebase_admin.initialize_app()
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}
FirebaseApp.Create();

初始化完成後,您可以使用 Admin SDK 執行下列類型的作業:

使用 OAuth 2.0 更新權杖

Admin SDK 也提供憑證,可讓您使用 Google OAuth2 更新權杖進行驗證:

Node.jsJavaPythonGoC#
const myRefreshToken = '...'; // Get refresh token from OAuth2 flow

initializeApp({
  credential: refreshToken(myRefreshToken),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
FileInputStream refreshToken = new FileInputStream("path/to/refreshToken.json");

FirebaseOptions options = FirebaseOptions.builder()
    .setCredentials(GoogleCredentials.fromStream(refreshToken))
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();

FirebaseApp.initializeApp(options);
cred = credentials.RefreshToken('path/to/refreshToken.json')
default_app = firebase_admin.initialize_app(cred)
opt := option.WithCredentialsFile("path/to/refreshToken.json")
config := &firebase.Config{ProjectID: "my-project-id"}
app, err := firebase.NewApp(context.Background(), config, opt)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}
FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile("path/to/refreshToken.json"),
});

在非 Google 環境中初始化 SDK

如果您在非 Google 伺服器環境中工作,且無法完全自動查詢預設憑證,您可以使用匯出的服務帳戶金鑰檔案,初始化 SDK。

Firebase 專案支援 Google 服務帳戶,您可以透過這些帳戶從應用程式伺服器或信任環境呼叫 Firebase 伺服器 API。如果您在本機開發程式碼,或將應用程式部署到內部部署,則可以使用透過此服務帳戶取得的憑證,授權伺服器要求。

如要驗證服務帳戶並授權存取 Firebase 服務,您必須以 JSON 格式產生私密金鑰檔案。

如何為服務帳戶產生私密金鑰檔案:

  1. Firebase 主控台中,依序開啟「設定」>「服務帳戶」

  2. 按一下「產生新的私密金鑰」,然後按一下「產生金鑰」確認。

  3. 妥善儲存含有金鑰的 JSON 檔案。

透過服務帳戶授權時,您可以透過兩種方式向應用程式提供憑證。您可以設定 GOOGLE_APPLICATION_CREDENTIALS 環境變數,也可以在程式碼中明確傳遞服務帳戶金鑰的路徑。第一個選項較為安全,強烈建議您採用。

如何設定環境變數:

將環境變數 GOOGLE_APPLICATION_CREDENTIALS 設為包含服務帳戶金鑰的 JSON 檔案路徑。此變數僅適用於您目前的殼層工作階段,因此如果您開啟新的工作階段,就必須再次設定變數。

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

完成上述步驟後,應用程式預設憑證 (ADC) 就能以隱密的方式判斷您的憑證,讓您在非 Google 環境中測試或執行時使用服務帳戶憑證。

請按照下圖所示初始化 SDK:

Node.jsJavaPythonGoC#
initializeApp({
    credential: applicationDefault(),
    databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
FirebaseOptions options = FirebaseOptions.builder()
    .setCredentials(GoogleCredentials.getApplicationDefault())
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();

FirebaseApp.initializeApp(options);
default_app = firebase_admin.initialize_app()
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}
FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
    ProjectId = "my-project-id",
});

初始化多個應用程式

在大多數情況下,您只需要初始化單一預設應用程式。您可以透過兩種等同方式存取該應用程式以外的服務:

Node.jsJavaPythonGoC#
// Initialize the default app
const defaultApp = initializeApp(defaultAppConfig);

console.log(defaultApp.name);  // '[DEFAULT]'

// Retrieve services via the defaultApp variable...
let defaultAuth = getAuth(defaultApp);
let defaultDatabase = getDatabase(defaultApp);

// ... or use the equivalent shorthand notation
defaultAuth = getAuth();
defaultDatabase = getDatabase();
// Initialize the default app
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);

System.out.println(defaultApp.getName());  // "[DEFAULT]"

// Retrieve services by passing the defaultApp variable...
FirebaseAuth defaultAuth = FirebaseAuth.getInstance(defaultApp);
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);

// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.getInstance();
defaultDatabase = FirebaseDatabase.getInstance();
# Import the Firebase service
from firebase_admin import auth

# Initialize the default app
default_app = firebase_admin.initialize_app(cred)
print(default_app.name)  # "[DEFAULT]"

# Retrieve services via the auth package...
# auth.create_custom_token(...)
// Initialize default app
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

// Access auth service from the default app
client, err := app.Auth(context.Background())
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}
// Initialize the default app
var defaultApp = FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
});
Console.WriteLine(defaultApp.Name); // "[DEFAULT]"

// Retrieve services by passing the defaultApp variable...
var defaultAuth = FirebaseAuth.GetAuth(defaultApp);

// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.DefaultInstance;

某些用途需要您同時建立多個應用程式。舉例來說,您可能想從某個 Firebase 專案的 Realtime Database 讀取資料,並為另一個專案鑄造自訂符記。或者,您可能想使用不同的憑證驗證兩個應用程式。Firebase SDK 可讓您同時建立多個應用程式,每個應用程式都有各自的設定資訊。

Node.jsJavaPythonGoC#
// Initialize the default app
initializeApp(defaultAppConfig);

// Initialize another app with a different config
var otherApp = initializeApp(otherAppConfig, 'other');

console.log(getApp().name);  // '[DEFAULT]'
console.log(otherApp.name);     // 'other'

// Use the shorthand notation to retrieve the default app's services
const defaultAuth = getAuth();
const defaultDatabase = getDatabase();

// Use the otherApp variable to retrieve the other app's services
const otherAuth = getAuth(otherApp);
const otherDatabase = getDatabase(otherApp);
// Initialize the default app
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);

// Initialize another app with a different config
FirebaseApp otherApp = FirebaseApp.initializeApp(otherAppConfig, "other");

System.out.println(defaultApp.getName());  // "[DEFAULT]"
System.out.println(otherApp.getName());    // "other"

// Use the shorthand notation to retrieve the default app's services
FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();

// Use the otherApp variable to retrieve the other app's services
FirebaseAuth otherAuth = FirebaseAuth.getInstance(otherApp);
FirebaseDatabase otherDatabase = FirebaseDatabase.getInstance(otherApp);
# Initialize the default app
default_app = firebase_admin.initialize_app(cred)

#  Initialize another app with a different config
other_app = firebase_admin.initialize_app(cred, name='other')

print(default_app.name)    # "[DEFAULT]"
print(other_app.name)      # "other"

# Retrieve default services via the auth package...
# auth.create_custom_token(...)

# Use the `app` argument to retrieve the other app's services
# auth.create_custom_token(..., app=other_app)
// Initialize the default app
defaultApp, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

// Initialize another app with a different config
opt := option.WithCredentialsFile("service-account-other.json")
otherApp, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

// Access Auth service from default app
defaultClient, err := defaultApp.Auth(context.Background())
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}

// Access auth service from other app
otherClient, err := otherApp.Auth(context.Background())
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}
// Initialize the default app
var defaultApp = FirebaseApp.Create(defaultOptions);

// Initialize another app with a different config
var otherApp = FirebaseApp.Create(otherAppConfig, "other");

Console.WriteLine(defaultApp.Name); // "[DEFAULT]"
Console.WriteLine(otherApp.Name); // "other"

// Use the shorthand notation to retrieve the default app's services
var defaultAuth = FirebaseAuth.DefaultInstance;

// Use the otherApp variable to retrieve the other app's services
var otherAuth = FirebaseAuth.GetAuth(otherApp);

設定 Realtime DatabaseAuthentication 的範圍

如果您使用 Google Compute Engine VM,並為 Realtime DatabaseAuthentication 設定 Google 應用程式預設憑證,請務必設定正確的存取權範圍。對於 Realtime DatabaseAuthentication,您需要結尾為 userinfo.email 的範圍,以及 cloud-platformfirebase.database。如要檢查現有的存取範圍並進行變更,請使用 gcloud 執行下列指令。

gcloud
# Check the existing access scopes
gcloud compute instances describe [INSTANCE_NAME] --format json

# The above command returns the service account information. For example:
  "serviceAccounts": [
   {
    "email": "your.gserviceaccount.com",
    "scopes": [
     "https://www.googleapis.com/auth/cloud-platform",
     "https://www.googleapis.com/auth/userinfo.email"
     ]
    }
  ],

# Stop the VM, then run the following command, using the service account
# that gcloud returned when you checked the scopes.

gcloud compute instances set-service-account [INSTANCE_NAME] --service-account "your.gserviceaccount.com" --scopes "https://www.googleapis.com/auth/firebase.database,https://www.googleapis.com/auth/userinfo.email"

使用 gcloud 使用者憑證進行測試

當您在本機測試 Admin SDK,並使用透過執行 gcloud auth application-default login 取得的 Google 應用程式預設憑證時,由於下列原因,您需要進行其他變更才能使用 Firebase Authentication

  • Firebase Authentication 不接受使用 gcloud OAuth 用戶端 ID 產生的 gcloud 使用者憑證。
  • Firebase Authentication 要求在初始化時提供這類使用者憑證的專案 ID。

解決方法是使用自己的 OAuth 2.0 用戶端 ID,在 gcloud 中產生 Google 應用程式預設憑證。OAuth 用戶端 ID 必須是「桌面應用程式」應用程式類型。

gcloud
gcloud auth application-default login --client-id-file=[/path/to/client/id/file]

您可以在應用程式初始化時明確指定專案 ID,也可以直接使用 GOOGLE_CLOUD_PROJECT 環境變數。後者可避免您需要進行任何額外變更來測試程式碼。

如要明確指定專案 ID:

Node.jsJavaPythonGoC#
import { initializeApp, applicationDefault } from 'firebase-admin/app';

initializeApp({
  credential: applicationDefault(),
  projectId: '<FIREBASE_PROJECT_ID>',
});
FirebaseOptions options = FirebaseOptions.builder()
    .setCredentials(GoogleCredentials.getApplicationDefault())
    .setProjectId("<FIREBASE_PROJECT_ID>")
    .build();

FirebaseApp.initializeApp(options);
app_options = {'projectId': '<FIREBASE_PROJECT_ID>'}
default_app = firebase_admin.initialize_app(options=app_options)
config := &firebase.Config{ProjectID: "<FIREBASE_PROJECT_ID>"}
app, err := firebase.NewApp(context.Background(), config)
if err != nil {
        log.Fatalf("error initializing app: %v\n", err)
}
FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
    ProjectId = "<FIREBASE_PROJECT_ID>",
});

後續步驟

瞭解 Firebase:

在應用程式中新增 Firebase 功能: