安装 Admin SDK

本文档介绍如何安装 Identity Platform Admin SDK。通过 Admin SDK,您可以从服务器环境管理 Identity Platform,并执行管理员操作,例如迁移用户、设置自定义声明和配置身份提供商。

准备工作

如需使用 Admin SDK,您需要一个运行以下任一项的服务器应用:

语言 最低框架版本
Node.js Node.js 8.13.0+
Java Java 7+(建议使用 Java 8+)
Python Python 2.7+ 或 3.4+(建议使用 3.4+)
Go Go 1.9+
C# .NET Framework 4.5+ 或 .NET Core 1.5+

下表列出了每种 SDK 语言支持的功能:

特征 Node.js Java Python Go C#
自定义令牌创建
ID 令牌验证
用户管理
使用自定义声明控制访问权限
刷新令牌撤消
导入用户
会话 Cookie 管理
生成电子邮件操作链接
管理 SAML/OIDC 提供方配置
多租户支持
Realtime Database *
Firebase Cloud Messaging
FCM 多播
管理 FCM 主题订阅
Cloud Storage
Firestore
项目管理
安全规则
机器学习模型管理
Firebase Remote Config
Firebase App Check
Firebase Extensions

此外,您还需要项目的服务账号和密钥:

控制台

创建服务帐号:

  1. 在 Google Cloud 控制台中,转到创建服务帐号页面。

    转到“创建服务帐号”
  2. 选择您的项目。
  3. 服务帐号名称字段中,输入一个名称。Google Cloud 控制台会根据此名称填充服务帐号 ID 字段。

    服务帐号说明字段中,输入说明。例如,Service account for quickstart

  4. 点击创建并继续
  5. Other > Identity Toolkit Admin 角色授予服务帐号。

    如需授予该角色,请找到选择角色列表,然后选择 Other > Identity Toolkit Admin

  6. 点击继续
  7. 点击完成以完成服务帐号的创建过程。

    不要关闭浏览器窗口。您将在下一步骤中用到它。

创建服务帐号密钥:

  1. 在 Google Cloud 控制台中,点击您创建的服务帐号的电子邮件地址。
  2. 点击密钥
  3. 点击添加密钥,然后点击创建新密钥
  4. 点击创建。JSON 密钥文件将下载到您的计算机上。
  5. 点击关闭

gcloud

设置身份验证:

  1. 创建服务帐号:

    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

    SERVICE_ACCOUNT_NAME 替换为服务帐号的名称。

  2. 向服务帐号授予 Project > Admin IAM 角色:

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=Project > Admin

    请替换以下内容:

    • SERVICE_ACCOUNT_NAME:服务帐号的名称
    • PROJECT_ID:您在其中创建服务帐号的项目的 ID
  3. 生成密钥文件:

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

    替换以下内容:

    • FILE_NAME:密钥文件的名称
    • SERVICE_ACCOUNT_NAME:服务帐号的名称
    • PROJECT_ID:您在其中创建服务帐号的项目的 ID

通过设置环境变量 GOOGLE_APPLICATION_CREDENTIALS 向应用代码提供身份验证凭据。此变量仅适用于当前的 Shell 会话。如果您希望变量应用于未来的 Shell 会话,请在 shell 启动文件中设置变量,例如在 ~/.bashrc~/.profile 文件中。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH 替换为包含凭据的 JSON 文件的路径。

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

对于 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

KEY_PATH 替换为包含凭据的 JSON 文件的路径。

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

对于命令提示符:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

KEY_PATH 替换为包含凭据的 JSON 文件的路径。

安装 SDK

Node.js

Node.js Admin SDK 可从 npm 上获得。如果您还没有 package.json 文件,请使用 npm init 创建一个。接下来,安装 npm 软件包并将其保存到 package.json

npm install firebase-admin --save

如需在应用中使用该模块,可从任意 JavaScript 文件对该模块执行 require

var admin = require('firebase-admin');

如果您使用的是 ES2015,则可以改为对该模块执行 import

import * as admin from 'firebase-admin';

Java

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

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

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

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

Python

可使用 pip 获取 Python Admin SDK。

pip install --user firebase-admin

Go

使用 go get 实用程序安装 Go Admin SDK:

go get firebase.google.com/go

C#

使用 .NET 软件包管理器安装 .NET Admin SDK:

Install-Package FirebaseAdmin -Version 1.9.1

您也可以使用 dotnet 命令行实用程序安装它:

dotnet add package FirebaseAdmin --version 1.9.1

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

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

使用默认凭据初始化 SDK

将以下代码添加到您的服务器应用,以使用默认凭据初始化 Admin SDK:

Node.js

// Initialize the default app
var admin = require('firebase-admin');
var app = admin.initializeApp({
  credential: admin.credential.applicationDefault()
});

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();

使用服务账号密钥文件初始化 SDK

您也可以手动指定服务账号密钥文件:

Node.js

// Initialize the default app
var admin = require('firebase-admin');
var app = admin.initializeApp({
  credential: admin.credential.cert('/path/to/serviceAccountKey.json')
});

Java

FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = FirebaseOptions.builder()
    .setCredentials(GoogleCredentials.fromStream(serviceAccount))
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();

FirebaseApp.initializeApp(options);

Python

import firebase_admin
from firebase_admin import credentials
from firebase_admin import exceptions

cred = credentials.Certificate('path/to/serviceAccountKey.json')
default_app = firebase_admin.initialize_app(cred)

Go

opt := option.WithCredentialsFile("path/to/serviceAccountKey.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

C#

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile("path/to/serviceAccountKey.json"),
});

初始化多个应用

通常,您只需要初始化一个默认应用。但是,您也可以创建多个应用实例,每个实例都有自己的配置选项和身份验证状态。

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();

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

设置范围

如果您将 Compute Engine 虚拟机与 Google 应用默认凭据一起用于身份验证,则需要设置适当的访问权限范围。Identity Platform 需要 userinfo.emailcloud-platform 访问权限范围。

如需检查现有的访问权限范围,请运行以下命令:

gcloud compute instances describe [INSTANCE-NAME] --format json

该命令将返回有关服务账号的信息。例如:

"serviceAccounts": [
 {
  "email": "example.gserviceaccount.com",
  "scopes": [
   "https://www.googleapis.com/auth/cloud-platform",
   "https://www.googleapis.com/auth/userinfo.email"
   ]
  }
]

如需更新访问权限范围,请停止虚拟机,然后运行以下命令:


gcloud compute instances set-service-account [INSTANCE-NAME] \
  --service-account "your.gserviceaccount.com" \
  --scopes ""https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email"

后续步骤