Admin SDK是一組服務器庫,可讓您從特權環境中與Firebase交互以執行以下操作:
- 具有完全管理員權限的讀寫實時數據庫數據。
- 使用Firebase Cloud Messaging服務器協議的簡單替代方法以編程方式發送Firebase Cloud Messaging消息。
- 生成並驗證Firebase身份驗證令牌。
- 訪問與您的Firebase項目關聯的Google Cloud資源,例如Cloud Storage存儲桶和Cloud Firestore數據庫。
- 創建您自己的簡化管理控制台,以執行諸如查找用戶數據或更改用戶的電子郵件地址進行身份驗證之類的操作。
如果您有興趣使用Node.js SDK作為客戶端(例如,在Node.js桌面或IoT應用程序中)進行最終用戶訪問,而不是通過特權環境(例如服務器)進行管理員訪問,則可以相反,應遵循有關設置客戶端JavaScript SDK的說明。
以下功能矩陣顯示了每種語言支持的Firebase功能:
特徵 | Node.js | 爪哇 | Python | 去 | C# |
---|---|---|---|---|---|
自定義令牌鑄造 | |||||
ID令牌驗證 | |||||
用戶管理 | |||||
使用自定義聲明控制訪問 | |||||
刷新令牌吊銷 | |||||
導入用戶 | |||||
會話Cookie管理 | |||||
生成電子郵件操作鏈接 | |||||
管理SAML / OIDC提供程序配置 | |||||
多租戶支持 | |||||
實時數據庫 | * | ||||
Firebase雲消息傳遞 | |||||
FCM組播 | |||||
管理FCM主題訂閱 | |||||
雲儲存 | |||||
Cloud Firestore | |||||
項目管理 | |||||
安全規則 | |||||
ML模型管理 | |||||
Firebase遠程配置 |
要了解有關這些用途的Admin SDK集成的更多信息,請參閱相應的Realtime Database , FCM , Authentication , Remote Config和Cloud Storage文檔。本頁面的其餘部分重點介紹Admin SDK的基本設置。
先決條件
確保您具有服務器應用程序。
確保服務器根據您使用的Admin SDK運行以下命令:
- Admin Node.js SDK-Node.js 10.10.0+
- Admin Java SDK-Java 7+(推薦Java 8+)
不推薦使用Java 7。 - Admin Python SDK-Python 3.5+(推薦Python 3.6+)
- Admin Go SDK-Go 1.11+
- 管理員.NET SDK-.NET Framework 4.5+或.Net Core 1.5+
設置Firebase項目和服務帳戶
要使用Firebase Admin SDK,您需要滿足以下條件:
- Firebase項目
- 與Firebase通信的服務帳戶
- 帶有服務帳戶憑據的配置文件
如果您還沒有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
要使用該模塊在應用程序中, require
從任何JavaScript文件:
var admin = require('firebase-admin');
如果您使用的是ES2015,則可以import
模塊:
import * as admin from 'firebase-admin';
爪哇
Firebase Admin Java SDK已發佈到Maven中央存儲庫。要安裝該庫,請在build.gradle
文件build.gradle
其聲明為依賴build.gradle
:
dependencies {
implementation 'com.google.firebase:firebase-admin:7.1.0'
}
如果使用Maven構建應用程序,則可以將以下依賴項添加到pom.xml
:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>7.1.0</version>
</dependency>
Python
可通過pip獲得Firebase Admin Python SDK。您可以通過sudo
為所有用戶安裝該庫:
$ sudo pip install firebase-admin
或者,您可以通過傳遞--user
標誌,僅為當前用戶安裝該庫:
$ pip install --user firebase-admin
去
可以使用go get
實用程序安裝Go Admin SDK:
# Install as a module dependency
$ go get firebase.google.com/go/v4
# Install to $GOPATH
$ go get firebase.google.com/go
C#
可以使用.NET軟件包管理器來安裝.NET Admin SDK:
$ Install-Package FirebaseAdmin -Version 2.0.0
或者,使用dotnet
命令行實用程序安裝它:
$ dotnet add package FirebaseAdmin --version 2.0.0
或者,可以通過將以下軟件包引用條目添加到.csproj
文件中來進行安裝:
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="2.0.0" />
</ItemGroup>
初始化SDK
創建Firebase項目後,您可以使用將您的服務帳戶文件和Google Application Default Credentials結合在一起的授權策略來初始化SDK。
Firebase項目支持Google服務帳戶,您可以使用這些帳戶從應用程序服務器或受信任的環境中調用Firebase服務器API。如果要在本地開發代碼或在本地部署應用程序,則可以使用通過此服務帳戶獲得的憑據來授權服務器請求。
要驗證服務帳戶並授權其訪問Firebase服務,您必須生成JSON格式的私鑰文件。
為您的服務帳戶生成私鑰文件:
在Firebase控制台中,打開“設置”>“服務帳戶” 。
單擊生成新私鑰,然後單擊生成密鑰進行確認。
安全地存儲包含密鑰的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
admin.initializeApp({
credential: admin.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(),
});
使用OAuth 2.0刷新令牌
Admin SDK還提供了一個憑證,可讓您使用Google OAuth2刷新令牌進行身份驗證:
Node.js
var refreshToken; // Get refresh token from OAuth2 flow
admin.initializeApp({
credential: admin.credential.refreshToken(refreshToken),
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"),
});
不帶參數初始化
SDK也可以不使用任何參數進行初始化。在這種情況下,SDK使用Google應用程序默認憑據。由於默認憑據查找在Google環境中是完全自動化的,不需要提供環境變量或其他配置,因此強烈建議在Compute Engine,Kubernetes Engine,App Engine和Cloud Functions上運行的應用程序採用這種初始化SDK的方式。
要為服務(例如實時數據庫,雲存儲或云功能)指定初始化選項,請使用FIREBASE_CONFIG
環境變量。如果FIREBASE_CONFIG
變量的內容以{
開頭,它將被解析為JSON對象。否則,SDK會假定該字符串是包含選項的JSON文件的路徑。
Node.js
// Initialize the default app
var admin = require('firebase-admin');
var app = admin.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完成以下類型的任務:
初始化多個應用
在大多數情況下,您只需要初始化一個默認應用即可。您可以通過兩種等效的方式訪問該應用程序的服務:
Node.js
// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);
console.log(defaultApp.name); // '[DEFAULT]'
// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();
// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();
爪哇
// 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
admin.initializeApp(defaultAppConfig);
// Initialize another app with a different config
var otherApp = admin.initializeApp(otherAppConfig, 'other');
console.log(admin.app().name); // '[DEFAULT]'
console.log(otherApp.name); // 'other'
// Use the shorthand notation to retrieve the default app's services
var defaultAuth = admin.auth();
var defaultDatabase = admin.database();
// Use the otherApp variable to retrieve the other app's services
var otherAuth = otherApp.auth();
var otherDatabase = otherApp.database();
爪哇
// 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虛擬機與用於實時數據庫或身份驗證的Google應用程序默認憑據一起使用,請確保還設置正確的訪問範圍。對於實時數據庫和身份驗證,您需要以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"
下一步
了解有關Firebase的信息:
閱讀Admin SDK的創建者之一與Admin SDK相關的博客文章。例如: 通過代理服務器訪問Firestore和Firebase 。
將Firebase功能添加到您的應用程序:
- 使用Cloud Functions編寫無服務器後端。
- 通過實時數據庫存儲信息,或通過Cloud Storage存儲blob數據。
- 通過Cloud Messaging接收通知。