將 Firebase Admin SDK 新增至伺服器

Admin SDK 是一組伺服器程式庫,可讓您從具特殊權限的環境與 Firebase 互動,執行下列操作:

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

如果您想使用 Node.js SDK 做為使用者存取權的用戶端 (例如在 Node.js 桌面或 IoT 應用程式中),而不是從具特殊權限的環境 (例如伺服器) 取得管理員存取權,請改為按照設定用戶端 JavaScript SDK 的操作說明進行。

以下功能矩陣顯示每種語言支援的 Firebase 功能:

功能 Node.js Java Python Go C# Dart
自訂權杖鑄造
ID 權杖驗證
使用者管理
使用自訂宣告控管存取權
撤銷更新權杖
匯入使用者
工作階段 Cookie 管理
產生電子郵件動作連結
管理 SAML/OIDC 提供者設定
多租戶支援
Firebase SQL Connect
Realtime Database *
Firebase Cloud Messaging
FCM 多點傳播
管理FCM主題訂閱項目
Cloud Storage
Cloud Firestore
使用 Cloud Tasks 將函式排入佇列
專案管理
安全性規則
機器學習模型管理
Firebase Remote Config
Firebase App Check
Firebase Extensions
Firebase Phone Number Verification

如要進一步瞭解如何整合 Admin SDK 以用於這些用途,請參閱 Realtime Database、FCM、Authentication、Remote Config 和 Cloud Storage 的相關說明文件。本頁其餘部分著重於 Admin SDK 的基本設定。

必要條件

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

  • 請確認伺服器執行的項目符合您使用的 Admin SDK:

    • Admin Node.js SDK - Node.js 22 以上版本
    • Admin Java SDK — Java 8+
    • Admin Python SDK:Python 3.9 以上版本 (建議使用 Python 3.10 以上版本)
      Python 3.9 支援已淘汰。
    • Admin Go SDK — Go 1.25+
    • Admin .NET SDK:.NET Framework 4.6.2 以上版本、.NET Standard 2.0 或 .NET 6.0 以上版本 (建議使用 .NET 8.0 以上版本)
      .NET 6.0 和 7.0 支援已淘汰。
    • 實驗性 Admin Dart SDK:請確認伺服器執行 Dart SDK 3.9 以上版本。

設定 Firebase 專案和服務帳戶

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

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

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

新增 SDK

如果您要設定新專案,則必須安裝所選語言的 SDK。

Node.js

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';

Java

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

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

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

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

Python

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

sudo pip install firebase-admin

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

pip install --user firebase-admin

Go

您可以使用 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.22.0

C#

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

Install-Package FirebaseAdmin -Version 3.7.0

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

dotnet add package FirebaseAdmin --version 3.7.0

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

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

Dart (實驗功能)

dart pub add firebase_admin_sdk

如要在應用程式中使用模組,請按照下列方式匯入:

import 'package:firebase_admin_sdk';

// Also import the separate Firestore package if you're interacting with Firestore.
import 'package:google_cloud_firestore/google_cloud_firestore.dart';

初始化 SDK

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

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

Node.js

const app = initializeApp();

Java

FirebaseApp.initializeApp();

Python

default_app = firebase_admin.initialize_app()

Go

app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

C#

FirebaseApp.Create();

Dart (實驗功能)

final admin = FirebaseApp.initializeApp();

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

使用 OAuth 2.0 更新權杖

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

Node.js

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

initializeApp({
  credential: refreshToken(myRefreshToken),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Java

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);

Python

cred = credentials.RefreshToken('path/to/refreshToken.json')
default_app = firebase_admin.initialize_app(cred)

Go

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)
}

C#

FirebaseApp.Create(new AppOptions()
{
    Credential = CredentialFactory.FromFile<UserCredential>("path/to/refreshToken.json").ToGoogleCredential(),
});

在非 Google 環境中初始化 SDK

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

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

您可以在 設定 >服務帳戶分頁中,查看 Firebase 專案的所有服務帳戶。

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

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

  1. 在 Firebase 控制台中,依序前往「 Settings」(設定) >「Service accounts tab」(服務帳戶分頁)。

  2. 按一下「Generate New Private Key」(產生新的私密金鑰),然後按一下「Generate Key」(產生金鑰) 進行確認。

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

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

如何設定環境變數:

將環境變數 GOOGLE_APPLICATION_CREDENTIALS 設為包含服務帳戶金鑰的 JSON 檔案路徑。這個變數只會套用至當前的殼層工作階段,因此如果開啟新的工作階段,請再次設定變數。

Linux 或 macOS

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

Windows

使用 PowerShell:

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

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

按照下列方式初始化 SDK:

Node.js

initializeApp({
    credential: applicationDefault(),
    databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Java

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

FirebaseApp.initializeApp(options);

Python

default_app = firebase_admin.initialize_app()

Go

app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

C#

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
    ProjectId = "my-project-id",
});

初始化多個應用程式

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

Node.js

// 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();

Java

// 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();

Python

# 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(...)

Go

// 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)
}

C#

// 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.js

// 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);

Java

// 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);

Python

# 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)

Go

// 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)
}

C#

// 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 Database 和 Authentication 的範圍

如果您使用 Google Compute Engine VM,並搭配 Realtime Database 或 Authentication 的 Google 應用程式預設憑證,請務必設定正確的存取權範圍。如要使用 Realtime Database 和 Authentication,您需要以 userinfo.email 和 cloud-platform 或 firebase.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 使用者憑證進行測試

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

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

如要解決這個問題,您可以在 gcloud 中使用自己的 OAuth 2.0 用戶端 ID 產生 Google 應用程式預設憑證。OAuth 用戶端 ID 必須是「電腦版應用程式」類型。

gcloud

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

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

如要明確指定專案 ID,請按照下列步驟操作:

Node.js

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

initializeApp({
  credential: applicationDefault(),
  projectId: '<FIREBASE_PROJECT_ID>',
});

Java

FirebaseOptions options = FirebaseOptions.builder()
    .setCredentials(GoogleCredentials.getApplicationDefault())
    .setProjectId("<FIREBASE_PROJECT_ID>")
    .build();

FirebaseApp.initializeApp(options);

Python

app_options = {'projectId': '<FIREBASE_PROJECT_ID>'}
default_app = firebase_admin.initialize_app(options=app_options)

Go

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)
}

C#

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
    ProjectId = "<FIREBASE_PROJECT_ID>",
});

後續步驟

瞭解 Firebase:

在應用程式中加入 Firebase 功能: