安裝 Admin SDK

本文說明如何安裝 Identity Platform Admin SDK。您可以透過管理員 SDK 從伺服器環境管理 Identity Platform,並執行管理員操作,例如遷移使用者、設定自訂憑證和設定 ID 提供者。

事前準備

如要使用 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 供應商設定
支援多租戶模式
即時資料庫 *
Firebase 雲端通訊
FCM 多播
管理 FCM 主題訂閱項目
Cloud Storage
Firestore
專案管理
安全性規則
機器學習模型管理
Firebase 遠端設定
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 VM 搭配 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"
   ]
  }
]

如要更新存取權範圍,請停止 VM,然後執行下列指令:


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"

後續步驟