Admin SDK 是一組伺服器程式庫,可讓您從具備權限的環境與 Firebase 互動,執行下列動作:
- 對Firebase Data Connect服務執行查詢和突變,以完整管理員權限進行大量資料管理和其他作業。
- 具備完整管理員權限,可讀取及寫入 Realtime Database 資料。
- 使用簡單的替代方法,以程式輔助方式傳送 Firebase Cloud Messaging 訊息,取代 Firebase Cloud Messaging 伺服器通訊協定。
- 產生及驗證 Firebase 驗證權杖。
- 存取與 Firebase 專案相關聯的 Google Cloud 資源,例如 Cloud Storage 值區和 Cloud Firestore 資料庫。
- 您可以建立自己的簡化版管理控制台,執行查詢使用者資料或變更使用者電子郵件地址以進行驗證等作業。
如果您想使用 Node.js SDK 做為用戶端,供使用者存取 (例如在 Node.js 電腦或物聯網應用程式中),而非從具備權限的環境 (例如伺服器) 進行管理員存取,請改為按照設定用戶端 JavaScript SDK 的操作說明操作。
下表列出各語言支援的 Firebase 功能:
如要進一步瞭解如何整合 Admin SDK 以用於這些用途,請參閱對應的Realtime Database、FCM、Authentication、Remote Config 和 Cloud Storage 說明文件。本頁其餘部分將著重於 Admin SDK 的基本設定。
事前準備
確認你擁有伺服器應用程式。
請確認伺服器執行下列項目,具體視您使用的 Admin SDK 而定:
- Admin Node.js SDK - Node.js 18 以上版本
- Admin Java SDK - Java 8 以上版本
- Admin Python SDK - Python 3.9 以上版本 (建議使用 Python 3.10 以上版本)
Python 3.9 支援已淘汰。 - Admin Go SDK - Go 1.23 以上版本
- 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 Central Repository。如要安裝程式庫,請在 build.gradle
檔案中將其宣告為依附元件:
dependencies {
implementation 'com.google.firebase:firebase-admin:9.5.0'
}
如果您使用 Maven 建構應用程式,可以將下列依附元件新增至 pom.xml
:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>9.5.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.17.0
C#
您可以使用 .NET 套件管理工具安裝 .NET Admin SDK:
Install-Package FirebaseAdmin -Version 3.3.0
或者,使用 dotnet
指令列公用程式安裝:
dotnet add package FirebaseAdmin --version 3.3.0
或者,您也可以在 .csproj
檔案中加入下列套件參照項目,藉此安裝:
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="3.3.0" />
</ItemGroup>
初始化 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();
初始化後,您可以使用 Admin SDK 完成下列類型的工作:
- 導入自訂驗證機制
- 管理 Firebase Authentication 使用者
- 對 Firebase Data Connect 服務執行管理查詢和突變。
- 從Realtime Database讀取及寫入資料
- 傳送訊息Firebase Cloud Messaging
使用 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 格式產生私密金鑰檔案。
如要為服務帳戶產生私密金鑰檔案,請按照下列步驟操作:
透過服務帳戶授權時,您可以選擇兩種方式,將憑證提供給應用程式。您可以設定 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 使用者憑證進行測試
在本機測試 Admin SDK 時,如果使用執行 gcloud auth application-default login
取得的 Google 應用程式預設憑證,則必須進行額外變更才能使用 Firebase Authentication,原因如下:
- Firebase Authentication 不接受使用 gcloud OAuth 用戶端 ID 產生的 gcloud 使用者憑證。
- Firebase Authentication 需要在初始化時提供專案 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 應用程式範例。
請參閱 Admin SDK 相關網誌文章,這些文章是由 Admin SDK 的其中一位創作者撰寫。例如: 透過 Proxy 伺服器存取 Firestore 和 Firebase。
在應用程式中新增 Firebase 功能:
- 使用 Cloud Functions 編寫無伺服器後端。
- 使用 Realtime Database 儲存資訊,或使用 Cloud Storage 儲存 Blob 資料。
- 透過 Cloud Messaging 接收通知。