Admin SDK 是一组服务器库,使您能够从特权环境与 Firebase 进行交互,以执行以下操作:
- 以完整管理员权限读写 Realtime Database 数据。
- 使用简单的替代方法以编程方式将 Firebase Cloud Messaging 消息发送至 Firebase Cloud Messaging 服务器协议。
- 生成并验证 Firebase 身份验证令牌。
- 访问 Google Cloud 资源,例如与您的 Firebase 项目相关联的 Cloud Storage 存储分区和 Cloud Firebase 数据库。
- 创建您自己的简化管理控制台,以执行查询用户数据或更改用户用于身份验证的电子邮件地址等操作。
如果您希望将 Node.js SDK 用作最终用户访问的客户端(例如,在 Node.js 桌面应用或 IoT 应用中),而不是用于特权环境(如服务器)下的管理员访问,则应该按照设置客户端 JavaScript SDK 的说明进行操作。
以下功能矩阵展示了每种语言支持哪些 Firebase 功能:
功能 | Node.js | Java | Python | Go | C# |
---|---|---|---|---|---|
自定义令牌创建 | |||||
ID 令牌验证 | |||||
用户管理 | |||||
使用自定义声明控制访问 | |||||
刷新令牌撤消 | |||||
导入用户 | |||||
会话 Cookie 管理 | |||||
生成电子邮件操作链接 | |||||
管理 SAML/OIDC 提供方配置 | |||||
多租户支持 | |||||
Realtime Database | * | ||||
Firebase Cloud Messaging | |||||
FCM 多播 | |||||
管理 FCM 主题订阅 | |||||
Cloud Storage | |||||
Cloud Firestore | |||||
项目管理 | |||||
安全规则 | |||||
机器学习模型管理 | |||||
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+
- Admin .NET SDK - .NET Framework 4.5+ 或 .Net Core 1.5+
设置 Firebase 项目和服务帐号
如需使用 Firebase Admin SDK,您需要具备以下项:
- 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
如需在应用中使用该模块,可从任意 JavaScript 文件对该模块执行 require
:
var admin = require('firebase-admin');
如果您使用的是 ES2015,则可以改为对该模块执行 import
:
import * as admin from 'firebase-admin';
Java
Firebase Admin Java SDK 已发布至 Maven 中央代码库。如需安装该库,请在 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
Firebase Admin Python SDK 可通过 pip 获得。您可以通过 sudo
为所有用户安装库:
$ sudo pip install firebase-admin
或者,您可以通过传递 --user
标志仅为当前用户安装库:
$ pip install --user firebase-admin
Go
您可以使用 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 应用默认凭据相结合的授权策略对 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"
Windows
使用 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'
});
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(),
});
使用 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'
});
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"),
});
在不使用参数的情况下进行初始化
该 SDK 也可以在不使用参数的情况下进行初始化。在这种情况下,该 SDK 使用 Google 应用默认凭据。由于默认凭据查询在 Google 环境中是完全自动化的,无需提供环境变量或其他配置,因此对于在 Compute Engine、Kubernetes Engine、App Engine 和 Cloud Functions 上运行的应用,强烈推荐使用这种方式初始化 SDK。
如需选择为 Realtime Database、Storage 或 Cloud Functions 等服务指定初始化选项,请使用 FIREBASE_CONFIG
环境变量。如果 FIREBASE_CONFIG
变量的内容以一个 {
开头,则会被解析为一个 JSON 对象。如果不是以该字符开头,则 SDK 会假定该字符串是包含选项的 JSON 文件的路径。
Node.js
// Initialize the default app
var admin = require('firebase-admin');
var app = admin.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 完成以下类型的任务:
初始化多个应用
在大多数情况下,您只需要初始化一个默认应用。您可以通过两种等效的方式利用该应用访问各项服务:
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();
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
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();
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 虚拟机与 Google 应用默认凭据一起用于 Realtime Database 或 Authentication,请确保您还设置了正确的访问权限范围。对于 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"
后续步骤
了解 Firebase:
探索 Firebase 应用示例。
阅读 Admin SDK 的其中一个创作者撰写的 Admin SDK 相关博文。例如:通过代理服务器访问 Firestore 和 Firebase。
为您的应用添加 Firebase 功能:
- 使用 Cloud Functions 编写无服务器后端。
- 使用 Realtime Database 存储信息,或使用 Cloud Storage 存储 blob 数据。
- 使用 Cloud Messaging 接收通知。