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 言語でサポートされている機能を示したものです。

機能 Node.js Java Python Go C#
カスタム トークンの作成
ID トークンの確認
ユーザー管理
カスタム クレームでアクセスを制御する
更新トークンを取り消す
ユーザーのインポート
セッション Cookie を管理する
メールのアクション リンクを生成する
SAML / OIDC プロバイダの構成を管理する
マルチテナンシーのサポート
Realtime Database *
Firebase Cloud Messaging
FCM マルチキャスト
FCM トピックのサブスクリプションの管理
Cloud Storage
Firestore
プロジェクト管理
セキュリティ ルール
ML モデルの管理
Firebase Remote Config
Firebase App Check
Firebase Extensions

コンソール

  1. サービス アカウントを作成します。

    1. サービス アカウントの作成者(roles/iam.serviceAccountCreator)IAM ロールとプロジェクト IAM 管理者(roles/resourcemanager.projectIamAdmin)IAM ロールがあることを確認します。ロールを付与する方法については、こちらをご覧ください
    2. コンソールで、[サービス アカウントの作成] ページに移動します。 Google Cloud

      [サービス アカウントの作成] に移動
    3. プロジェクトを選択します。
    4. [サービス アカウント名] フィールドに名前を入力します。コンソールでは、この名前に基づいて [サービス アカウント ID] フィールドの値が設定されます。 Google Cloud

      [サービス アカウントの説明] フィールドに説明を入力します。例: Service account for quickstart

    5. [作成して続行] をクリックします。
    6. サービス アカウントに [その他 > Identity Toolkit 管理者] ロールを付与します。

      ロールを付与するには、[ロールを選択] リストで [その他 > Identity Toolkit 管理者] を選択します。

    7. [続行] をクリックします。
    8. [完了] をクリックして、サービス アカウントの作成を完了します。

      ブラウザ ウィンドウは閉じないでください。次のステップでこれを使用します。

  2. サービス アカウント キーを作成します。

    1. コンソールで、作成したサービス アカウントのメールアドレスをクリックします。 Google Cloud
    2. [キー] をクリックします。
    3. [鍵を追加]、[新しい鍵を作成] の順にクリックします。
    4. [作成] をクリックします。JSON キーファイルがパソコンにダウンロードされます。
    5. [閉じる] をクリックします。

gcloud

  1. 認証を設定します。

    1. サービス アカウントの作成者 (roles/iam.serviceAccountCreator)IAM ロールとプロジェクト IAM 管理者 (roles/resourcemanager.projectIamAdmin)IAM ロールがあることを確認します。ロールを付与する方法については、こちらをご覧ください
    2. サービス アカウントを作成します。

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME をサービス アカウントの名前に置き換えます。

    3. サービス アカウントに roles/identitytoolkit.admin IAM ロールを付与します。

      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
    4. 鍵ファイルを生成します。

      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 中央リポジトリに公開されています。ライブラリをインストールするには、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 = CredentialFactory.FromFile<ServiceAccountCredential>("path/to/serviceAccountKey.json").ToGoogleCredential(),
});

複数のアプリの初期化

通常は、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"

次のステップ