安裝 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:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator
). Learn how to grant roles. -
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.
-
Ensure that you have the Create Service Accounts IAM role
(
-
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:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator
). Learn how to grant roles. -
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
roles/identitytoolkit.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=roles/identitytoolkit.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
-
Ensure that you have the Create Service Accounts IAM role
(
安裝 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 = 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.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 租戶