安裝 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 語言支援的功能:
控制台
-
建立服務帳戶:
-
確認您具備「建立服務帳戶」身分與存取權管理角色 (
roles/iam.serviceAccountCreator) 和「專案 IAM 管理員」角色 (roles/resourcemanager.projectIamAdmin)。瞭解如何授予角色。 -
前往 Google Cloud 控制台的「Create service account」(建立服務帳戶) 頁面。
前往「建立服務帳戶」 - 選取專案。
-
在「Service account name」(服務帳戶名稱) 欄位中輸入名稱。 Google Cloud 控制台會將這個名稱填入「Service account ID」(服務帳戶 ID) 欄位。
在「Service account description」(服務帳戶說明) 欄位中輸入說明。例如:
Service account for quickstart。 - 按一下「建立並繼續」。
-
將「Other」(其他) >「Identity Toolkit Admin」(身分識別工具包管理員) 角色授予服務帳戶。
如要授予角色,請找出「Select a role」(選取角色) 清單,然後選取「Other」(其他) >「Identity Toolkit Admin」(身分識別工具包管理員)。
- 按一下 [繼續]。
-
按一下「Done」(完成),即完成建立服務帳戶。
請勿關閉瀏覽器視窗,您會在下一個步驟中使用此項目。
-
確認您具備「建立服務帳戶」身分與存取權管理角色 (
-
建立服務帳戶金鑰:
- 在 Google Cloud 控制台中,點按您建立的服務帳戶電子郵件地址。
- 按一下「Keys」(金鑰)。
- 依序點按「Add key」(新增金鑰) 和「Create new key」(建立新的金鑰)。
- 點按「Create」(建立)。系統會將 JSON 金鑰檔案下載至您的電腦。
- 按一下「關閉」。
gcloud
-
設定驗證方法:
-
確認您具備「建立服務帳戶」身分與存取權管理角色 (
roles/iam.serviceAccountCreator) 和「專案 IAM 管理員」角色 (roles/resourcemanager.projectIamAdmin)。瞭解如何授予角色。 -
建立服務帳戶:
gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
將
SERVICE_ACCOUNT_NAME換成服務帳戶的名稱。 -
將
roles/identitytoolkit.admin身分與存取權管理角色授予服務帳戶:gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/identitytoolkit.admin
請替換下列項目:
SERVICE_ACCOUNT_NAME:服務帳戶名稱PROJECT_ID:您建立服務帳戶的專案 ID
-
產生金鑰檔案:
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
-
確認您具備「建立服務帳戶」身分與存取權管理角色 (
安裝 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 Central Repository。如要安裝程式庫,請在 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 = CredentialFactory.FromFile<ServiceAccountCredential>("path/to/serviceAccountKey.json").ToGoogleCredential(), });
初始化多個應用程式
一般來說,您只會想初始化單一預設應用程式。不過,您也可以建立多個應用程式例項,每個例項都有自己的設定選項和驗證狀態。
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.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"
]
}
]
如要更新存取權範圍,請停止 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"
後續步驟
- 在 GitHub 上查看 Admin SDK 的原始碼和額外說明文件:
- 將現有使用者遷移至 Identity Platform
- 透過程式管理 SAML 和 OIDC 供應商
- 管理 Identity Platform 租戶