將 Firebase Admin SDK 新增至伺服器

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

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

如果您想使用 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 擴充功能

如要進一步瞭解如何整合這些用途的 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 6.0 以上版本適用的 .NET Standard 2.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/v4@4.14.1

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 環境中,預設憑證查詢是完全自動化的,您不需要提供環境變數或其他設定,因此對於在 Cloud Run、App Engine 和 Cloud Functions 等 Google 環境中執行的應用程式,強烈建議採用這種方式初始化 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 控制台中,依序開啟「Settings」>「Service Accounts」(服務帳戶)

  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 驗證,您必須在初始化時提供這些類型的使用者憑證。

為解決這個問題,您可以在 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 功能: