將 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.12.1

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 功能添加到您的應用: