安装 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

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

控制台

Create a service account:

  1. In the Google Cloud console, go to the Create service account page.

    Go to Create service account
  2. Select your project.
  3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

    In the Service account description field, enter a description. For example, Service account for quickstart.

  4. Click Create and continue.
  5. Grant the Other > Identity Toolkit Admin role to the service account.

    To grant the role, find the Select a role list, then select Other > Identity Toolkit Admin.

  6. Click Continue.
  7. Click Done to finish creating the service account.

    Do not close your browser window. You will use it in the next step.

Create a service account key:

  1. In the Google Cloud console, click the email address for the service account that you created.
  2. Click Keys.
  3. Click Add key, and then click Create new key.
  4. Click Create. A JSON key file is downloaded to your computer.
  5. Click Close.

gcloud

Set up authentication:

  1. Create the service account:

    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

    Replace SERVICE_ACCOUNT_NAME with a name for the service account.

  2. Grant the Project > Admin IAM role to the service account:

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

    Replace the following:

    • SERVICE_ACCOUNT_NAME: the name of the service account
    • PROJECT_ID: the project ID where you created the service account
  3. Generate the key file:

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

    Replace the following:

    • FILE_NAME: a name for the key file
    • SERVICE_ACCOUNT_NAME: the name of the service account
    • PROJECT_ID: the project ID where you created the service account

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. This variable applies only to your current shell session. If you want the variable to apply to future shell sessions, set the variable in your shell startup file, for example in the ~/.bashrc or ~/.profile file.

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

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

Windows

For PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

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

For command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Replace KEY_PATH with the path of the JSON file that contains your credentials.

安装 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"

后续步骤