Admin SDK をインストールする
このドキュメントでは、Identity Platform Admin SDK をインストールする方法について説明します。Admin 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 言語でサポートされている機能を示したものです。
さらに、プロジェクトのサービス アカウントとキーが必要です。
Console
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
環境変数 GOOGLE_APPLICATION_CREDENTIALS
を設定して、アプリケーション コードに認証情報を指定します。この変数は、現在のシェル セッションにのみ適用されます。この変数を新しいシェル セッションに適用する場合は、シェル起動ファイル(~/.bashrc
ファイルや ~/.profile
ファイルなど)で変数を設定します。
Linux または macOS
export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH
"
KEY_PATH
は、認証情報が含まれる JSON ファイルのパスに置き換えます。
例:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
Windows
PowerShell の場合:
$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH
"
KEY_PATH
は、認証情報が含まれる JSON ファイルのパスに置き換えます。
例:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
コマンド プロンプトの場合:
set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
KEY_PATH
は、認証情報が含まれる JSON ファイルのパスに置き換えます。
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
Python Admin SDK は pip を使用して入手可能です。
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"), });
複数のアプリの初期化
通常は、1 つのデフォルト アプリのみを初期化するようにします。ただし、それぞれ独自の構成オプションと認証状態を持つ複数のアプリ インスタンスを作成することもできます。
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);
スコープの設定
認証に Google アプリケーションのデフォルト認証情報を使用する Compute Engine VM を使用している場合は、適切なアクセス スコープを設定する必要があります。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 テナントを管理する。