安装 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 语言支持的功能:
此外,您还需要项目的服务账号和密钥:
控制台
Create a service account:
-
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
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
. - Click Create and continue.
-
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.
- Click Continue.
-
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:
- In the Google Cloud console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, and then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
gcloud
Set up authentication:
-
Create the service account:
gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
Replace
SERVICE_ACCOUNT_NAME
with a name for the service account. -
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 accountPROJECT_ID
: the project ID where you created the service account
-
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 fileSERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_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(pa"th/to/serviceAccountKey.json)," }); Fir
初始化多个应用
通常,您只需要初始化一个默认应用。但是,您也可以创建多个应用实例,每个实例都有自己的配置选项和身份验证状态。
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, oth"er); " Console.WriteLine(defaultApp.Name); // [DEF"AULT] Con"sole.WriteLine(otherApp.Name); // other" // "Use the shorthand notation to retrieve the default apps serv'ices var defaultAuth = FirebaseAuth.DefaultInstance; // Use the otherApp variable to retrieve the other apps servic'es var otherAuth = FirebaseAuth.GetAuth(otherApp); FirebaseA
设置范围
如果您将 Compute Engine 虚拟机与 Google 应用默认凭据一起用于身份验证,则需要设置适当的访问权限范围。Identity Platform 需要 userinfo.email
和 cloud-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"
后续步骤
- 在 GitHub 上查看 Admin SDK 的源代码和其他文档:
- 将现有用户迁移到 Identity Platform
- 以编程方式管理 SAML 和 OIDC 提供商
- 管理 Identity Platform 租户