將 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爪哇PythonC#
客製化代幣鑄造
ID令牌驗證
使用者管理
使用自訂聲明控制訪問
刷新令牌撤銷
導入用戶
會話 Cookie 管理
產生電子郵件操作連結
管理 SAML/OIDC 提供者配置
多租戶支持
即時資料庫 *
Firebase 雲端訊息傳遞
FCM組播
管理 FCM 主題訂閱
雲端儲存
雲端Firestore
專案管理
安全規則
機器學習模型管理
Firebase 遠端配置
Firebase 應用程式檢查
Firebase 擴充

要了解有關這些用途的 Admin SDK 整合的更多信息,請參閱相應的Realtime DatabaseFCMAuthenticationRemote ConfigCloud Storage文件。本頁的其餘部分重點介紹 Admin SDK 的基本設定。

先決條件

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

  • 確保您的伺服器根據您使用的 Admin SDK 執行以下命令:

    • 管理 Node.js SDK — Node.js 14+
    • 管理 Java SDK — Java 8+
    • 管理 Python SDK — Python 3.6+(建議 Python 3.7+)
    • 管理員 Go SDK — Go 1.17+
    • 管理 .NET SDK — .NET Framework 4.6.1+ 或 .NET Standard 2.0 for .Net Core 2.0+

設定 Firebase 專案和服務帳戶

要使用 Firebase Admin SDK,您需要以下內容:

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

如果您還沒有 Firebase 項目,則需要在Firebase 控制台中建立一個。請造訪了解 Firebase 專案以了解有關 Firebase 專案的更多資訊。

新增SDK

如果您要設定新項目,則需要安裝適合您選擇的語言的 SDK。

Node.js

Firebase 管理 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.2.0'
}

如果您使用 Maven 建立應用程序,則可以將下列依賴項新增至pom.xml

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

Python

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

sudo pip install firebase-admin

或者,您可以透過傳遞--user標誌來僅為目前使用者安裝該庫:

pip install --user firebase-admin

可以使用go install實用程式安裝 Go Admin SDK:

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

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

C#

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

Install-Package FirebaseAdmin -Version 2.4.0

或者,使用dotnet命令列實用程式安裝它:

dotnet add package FirebaseAdmin --version 2.4.0

或者,您可以透過將以下套件引用條目新增至.csproj檔案來安裝它:

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

初始化SDK

建立 Firebase 專案後,您可以使用Google Application Default Credentials初始化 SDK。由於預設憑證查找在Google 環境中是完全自動化的,無需提供環境變數或其他配置,因此強烈建議在Google 環境(例如Cloud Run、App Engine 和Cloud Functions)中執行的應用程式使用此初始化SDK 的方式。

若要選擇性地指定即時資料庫、雲端儲存或雲端函數等服務的初始化選項,請使用FIREBASE_CONFIG環境變數。如果FIREBASE_CONFIG變數的內容以{開頭,它將被解析為 JSON 物件。否則,SDK 假定該字串是包含選項的 JSON 檔案的路徑。

Node.js

const app = initializeApp();

爪哇

FirebaseApp.initializeApp();

Python

default_app = firebase_admin.initialize_app()

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

爪哇

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)

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 檔案的檔案路徑。此變數僅適用於目前的 shell 會話,因此如果您開啟新會話,請再次設定該變數。

Linux 或 macOS

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

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

Python

default_app = firebase_admin.initialize_app()

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

爪哇

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

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

爪哇

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

// 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.emailcloud-platformfirebase.database結尾的範圍。若要檢查現有存取範圍並變更它們,請使用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 用戶端 IDgcloud中產生 Google 應用程式預設憑證。 OAuth 用戶端 ID 必須是桌面應用程式應用程式類型。

雲雲

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>',
});

爪哇

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)

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 功能新增至您的應用程式: