将 Firebase Admin SDK 添加到您的服务器

Admin SDK 是一组服务器库,让您可以从特权环境与 Firebase 进行交互,以执行以下操作:

  • 以完整管理员权限对 Firebase Data Connect 服务执行查询和变更操作,以便进行批量数据管理和其他操作。
  • 以完整管理员权限读写 Realtime Database 数据。
  • 使用 Firebase Cloud Messaging 服务器协议的简单替代方法以编程方式发送 Firebase Cloud Messaging 消息。
  • 生成并验证 Firebase 身份验证令牌。
  • 访问 Google Cloud 资源,例如与您的 Firebase 项目相关联的 Cloud Storage 存储桶和 Cloud Firestore 数据库。
  • 创建您自己的简化管理控制台,以执行用户数据查询或更改用户的身份验证电子邮件地址等操作。

如果您希望将 Node.js SDK 用作最终用户访问的客户端(例如,在 Node.js 桌面应用或 IoT 应用中),而不是用于特权环境(如服务器)下的管理员访问,则应该按照设置客户端 JavaScript SDK 的说明进行操作。

以下功能矩阵展示了每种语言支持哪些 Firebase 功能:

如需详细了解用于这些用途的 Admin SDK 集成,请参阅相应的 Realtime DatabaseFCMAuthenticationRemote ConfigCloud Storage 文档。本页面的其余部分重点介绍 Admin SDK 的基本设置。

前提条件

  • 确保您拥有服务器应用。

  • 确保您的服务器运行以下环境或框架(具体取决于您使用的 Admin SDK):

    • Admin Node.js SDK — Node.js 18+
    • Admin Java SDK — Java 8+
    • Admin Python SDK - Python 3.7+(建议使用 Python 3.8+)
      Python 3.7 支持已弃用。
    • Admin Go SDK — Go 1.21+
    • 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 项目以了解详情。

  1. Firebase 控制台中,点击添加项目

    • 如需将 Firebase 资源添加到现有 Google Cloud 项目,请输入该项目的名称或从下拉菜单中选择该项目。

    • 如需创建新项目,请输入要使用的项目名称。您也可以视需要修改项目名称下方显示的项目 ID。

  2. 如果看到相关提示,请查看并接受 Firebase 条款

  3. 点击继续

  4. (可选)为您的项目设置 Google Analytics,以便在使用下列 Firebase 产品时能获得最佳体验:

    选择现有的 Google Analytics 账号,或者创建一个新账号。

    如果您选择创建一个新账号,请选择 Analytics 报告位置,然后接受项目的数据共享设置和 Google Analytics 条款。

  5. 点击创建项目(或者,如果您使用的是现有 Google Cloud 项目,则点击添加 Firebase)。

Firebase 会自动为您的 Firebase 项目预配资源。完成此过程后,您将进入 Firebase 控制台中该 Firebase 项目的概览页面。

添加 SDK

如果您是在设置新项目,则需要安装所选语言的 SDK。

Node.jsJavaPythonGoC#

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

Firebase Admin Java SDK 已发布至 Maven 中央存储库。如需安装该库,请在 build.gradle 文件中将其声明为依赖项:

dependencies {
  implementation 'com.google.firebase:firebase-admin:9.4.3'
}

如果您使用 Maven 构建应用,可以将以下依赖项添加到 pom.xml

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

Firebase Admin Python SDK 可通过 pip 获得。您可以通过 sudo 为所有用户安装该库:

sudo pip install firebase-admin

或者,您可以通过传递 --user 标志仅为当前用户安装该库:

pip install --user firebase-admin

您可以使用 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.15.2

您可以使用 .NET 软件包管理系统安装 .NET Admin SDK

Install-Package FirebaseAdmin -Version 3.1.0

您也可以使用 dotnet 命令行工具来安装:

dotnet add package FirebaseAdmin --version 3.1.0

或者,您可以通过将以下软件包引用条目添加到 .csproj 文件来安装:

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

初始化 SDK

创建 Firebase 项目后,您可以使用 Google 应用默认凭据初始化 SDK。由于默认凭据查询在 Google 环境中是完全自动化的,无需提供环境变量或其他配置,因此对于在 Google 环境(例如 Cloud Run、App Engine 和 Cloud Functions)中运行的应用,强烈建议采用这种方式来初始化 SDK。

如需选择为 Realtime DatabaseCloud StorageCloud Functions 等服务指定初始化选项,请使用 FIREBASE_CONFIG 环境变量。如果 FIREBASE_CONFIG 变量的内容以 { 开头,则会被解析为 JSON 对象。如果不是以该字符开头,则 SDK 会假定该字符串是包含选项的 JSON 文件的路径。

Node.jsJavaPythonGoC#
const app = initializeApp();
FirebaseApp.initializeApp();
default_app = firebase_admin.initialize_app()
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}
FirebaseApp.Create();

初始化后,您可以使用 Admin SDK 完成以下类型的任务:

使用 OAuth 2.0 刷新令牌

Admin SDK 还提供一个凭据,使您能够使用 Google OAuth2 刷新令牌进行身份验证:

Node.jsJavaPythonGoC#
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);
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)
}
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 或 macOSWindows
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.jsJavaPythonGoC#
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);
default_app = firebase_admin.initialize_app()
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}
FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
    ProjectId = "my-project-id",
});

初始化多个应用

在大多数情况下,您只需要初始化一个默认应用。您可以通过两种等效的方式利用该应用访问各项服务:

Node.jsJavaPythonGoC#
// 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();
# 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)
}
// 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.jsJavaPythonGoC#
// 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);
# 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)
}
// 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 DatabaseAuthentication 设置范围

如果您将 Google Compute Engine 虚拟机与 Google 应用默认凭据一起用于 Realtime DatabaseAuthentication,请确保您还设置了正确的访问权限范围。对于 Realtime DatabaseAuthentication,您需要以 userinfo.emailcloud-platformfirebase.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 最终用户凭据进行测试

使用运行 gcloud auth application-default login 获得的 Google 应用默认凭据在本地测试 Admin SDK 时,需要对该凭据进行额外的更改才能使用 Firebase Authentication,原因如下:

  • Firebase Authentication 不接受使用 gcloud OAuth 客户端 ID 生成的 gcloud 最终用户凭据。
  • Firebase Authentication 要求在初始化时针对这些类型的最终用户凭据提供项目 ID。

如需解决此问题,您可以使用自己的 OAuth 2.0 客户端 IDgcloud 中生成 Google 应用默认凭据。OAuth 客户端 ID 必须是桌面应用类型。

gcloud
gcloud auth application-default login --client-id-file=[/path/to/client/id/file]

您可以在应用初始化时明确指定项目 ID,也可以仅使用 GOOGLE_CLOUD_PROJECT 环境变量。如果您采用上述的第二种方式,那么无需进行任何其他更改即可测试代码。

如需明确指定项目 ID,请执行以下操作:

Node.jsJavaPythonGoC#
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);
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)
}
FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
    ProjectId = "<FIREBASE_PROJECT_ID>",
});

后续步骤

了解 Firebase:

为您的应用添加 Firebase 功能: