將 Firebase Admin SDK 新增至伺服器

Admin SDK 是一組伺服器程式庫,可讓您透過特殊權限環境與 Firebase 互動,以便執行以下動作:

  • 以完整管理員權限讀取及寫入即時資料庫資料。
  • 使用可替代的替代方法,以程式輔助方式傳送 Firebase 雲端通訊訊息至 Firebase 雲端通訊伺服器通訊協定。
  • 產生並驗證 Firebase 驗證權杖。
  • 存取與 Firebase 專案相關聯的 Cloud Storage 值區和 Cloud Firestore 資料庫等 Google Cloud 資源。
  • 建立自己的簡化管理控制台,以便查詢使用者資料,或變更使用者的電子郵件地址以進行驗證。

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

以下為特徵矩陣,顯示各個語言支援的 Firebase 功能:

功能 Node.js Java Python Go C#
自訂權杖探究
ID 權杖驗證
使用者管理
使用自訂版權聲明控管存取權
更新權杖撤銷
匯入使用者
工作階段 Cookie 管理
產生電子郵件動作連結
管理 SAML/OIDC 供應商設定
支援多用戶群架構
即時資料庫 *
Firebase 雲端通訊
FCM 多點傳送
管理 FCM 主題訂閱項目
Cloud Storage
Cloud Firestore
使用 Cloud Tasks 將函式排入佇列
專案管理
安全性規則
機器學習模型管理
Firebase 遠端設定
Firebase App Check
Firebase Extensions

如要進一步瞭解上述用途的 Admin SDK 整合,請參閱對應的即時資料庫FCM驗證遠端設定Cloud Storage 說明文件。本頁面的其餘部分將著重介紹 Admin SDK 的基本設定。

事前準備

  • 確認您已安裝伺服器應用程式。

  • 請確保您的伺服器依據您使用的 Admin SDK 執行以下作業:

    • Admin Node.js SDK - Node.js 14 以上版本 (建議 Node.js 16 以上版本)
      Node.js 14 支援已淘汰。
    • Admin Java SDK - Java 8 以上版本
    • Admin Python SDK - Python 3.7 以上版本 (建議使用 Python 3.8 以上版本)
      Python 3.7 支援功能已淘汰。
    • Admin Go SDK - Go 1.20 以上版本
    • Admin .NET SDK - .NET Framework 4.6.2 以上版本或 .NET Standard 2.0 (適用於 .NET 6.0 以上版本)

設定 Firebase 專案和服務帳戶

如要使用 Firebase Admin SDK,您必須具備:

  • Firebase 專案。
  • 要與 Firebase 通訊的 Firebase Admin SDK 服務帳戶。當您建立 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.3.0'
}

如果您使用 Maven 建構應用程式,可以在 pom.xml 中加入以下依附元件:

<dependency>
  <groupId>com.google.firebase</groupId>
  <artifactId>firebase-admin</artifactId>
  <version>9.3.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/[email protected]

C#

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

Install-Package FirebaseAdmin -Version 3.0.0

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

dotnet add package FirebaseAdmin --version 3.0.0

或者,您也可以將下列套件參照項目新增至 .csproj 檔案,即可安裝該套件:

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

初始化 SDK

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

如要選擇為即時資料庫、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();

初始化完成後,您就能使用 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 = 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 檔案路徑。此變數僅適用於目前的殼層工作階段,因此如果您開啟新的工作階段,請再次設定變數。

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 專案的即時資料庫中的資料,並產生另一個專案的自訂權杖。或者,您可能希望使用不同憑證驗證兩個應用程式。您可以利用 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);

設定即時資料庫和驗證的範圍

如果您使用 Google Compute Engine VM 搭配即時資料庫或驗證的 Google 應用程式預設憑證,請務必一併設定正確的存取權範圍。如要進行即時資料庫和驗證,您需要以 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 使用者憑證進行測試

在本機使用執行 gcloud auth application-default login 取得的 Google 應用程式預設憑證測試 Admin SDK 時,您必須進行其他變更,才能使用 Firebase 驗證。原因如下:

  • Firebase 驗證不接受使用 gcloud OAuth 用戶端 ID 產生的 gcloud 使用者憑證。
  • Firebase 驗證需要在初始化時提供專案 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.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 功能: