Admin SDK を使用すると、特権環境から Firebase と対話し、次のような操作を行うことができます。
- Realtime Database のデータの読み取りと書き込みを完全な管理者権限で実行する。
- FCM サーバー プロトコルに対する簡単な代替アプローチを使用して、プログラムにより Firebase Cloud Messaging メッセージを送信する。
- Firebase Auth トークンを生成し確認する。
- Google Cloud Platform リソース(Cloud Storage バケットや、Firebase プロジェクトに関連付けられた Firebase データベースなど)にアクセスする。
- 独自の簡単な管理コンソールを作成して、認証のためにユーザーデータの検索やユーザーのメールアドレス変更などの作業を行う。
特権環境(サーバーなど)からの管理者アクセスではなく、エンドユーザー アクセスのクライアントとして Node.js SDK を使用することを検討している場合(Node.js デスクトップ、IoT アプリケーションなど)、このドキュメントではなく、クライアント JavaScript SDK の設定に関する手順をご覧ください。
以下に、各言語でサポートされている Firebase 機能を示す機能マトリックスを示します。
この用途で Admin SDK を統合する方法については、対応する Realtime Database、FCM、Authentication、Cloud Storage のドキュメントをご覧ください。このページの残りの部分では、Admin SDK の基本的なセットアップに焦点を当てます。
事前準備
Firebase を追加する前に、次の準備をしてください。
- Admin Node.js SDK を使用する場合は、Node.js 6.0 以降を実行するサーバー
- Admin Java SDK を使用する場合は、Java 7 以降を実行するサーバー
- Admin Python SDK を使用する場合は、Python 2.7 以降または 3.4 以降を実行するサーバー
- Admin Go SDK を使用する場合は、Go 1.9 以降を実行するサーバー
- Admin .NET SDK を使用する場合は、.NET Framework 4.5 以降または .Net Core 1.5 以降を実行するサーバー
- サーバーアプリ
アプリに Firebase を追加する
Firebase Admin SDK を使用するには、Firebase プロジェクト、Firebase サービスと通信するためのサービス アカウント、サービス アカウントの認証情報が設定された構成ファイルが必要です。
- Firebase プロジェクトをまだ作成していない場合は、Firebase コンソールでプロジェクトを作成します。[プロジェクトを追加] ダイアログでも、既存の Google Cloud Platform プロジェクトに Firebase を追加できます。
- プロジェクトの設定ページの [サービス アカウント] タブに移動します。
- [サービス アカウント] タブの [Firebase Admin SDK] セクション下部にある [新しい秘密鍵を生成] ボタンをクリックします。
ボタンをクリックすると、サービス アカウントの認証情報を含む JSON ファイルがダウンロードされます。この認証情報は、次のステップで SDK を初期化する際に必要です。
このファイルは一度だけ生成されます。この鍵が紛失または漏えいした場合は、上記の手順を繰り返して、サービス アカウント用の新しい JSON 鍵を作成できます。
SDK を追加する
新しいプロジェクトを設定する場合は、選択した言語の SDK をインストールする必要があります。
Node.js
Firebase Admin Node.js SDK は npm で利用可能です。まだ package.json ファイルがない場合は、npm init でそれを作成してください。次に、firebase-admin npm パッケージをインストールして package.json に保存します。
$ npm install firebase-admin --save
アプリケーションでモジュールを使用するには、任意の JavaScript ファイルから次のようにモジュールを require します。
var admin = require('firebase-admin');
あるいは ES2015 を使用している場合は、次のようにモジュールを import できます。
import * as admin from 'firebase-admin';
Java
Firebase Admin Java SDK は Maven 中央リポジトリに公開されます。ライブラリをインストールするには、build.gradle ファイル内で次のように依存関係としてそれを宣言します。
dependencies {
implementation 'com.google.firebase:firebase-admin:6.8.0'
}
Maven を使用してアプリケーションを構築する場合は、次の依存関係を pom.xml に追加します。
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.8.0</version>
</dependency>
Python
Firebase Admin Python SDK は pip を利用して入手できます。sudo を使用すれば、すべてのユーザーのライブラリをインストールできます。
$ sudo pip install firebase-admin
または、--user フラグを渡して現在のユーザーだけのライブラリをインストールすることもできます。
$ pip install --user firebase-admin
Go
Go Admin SDK は、go get ユーティリティを使用してインストールできます。
$ go get firebase.google.com/go
C#
.NET Admin SDK は、.NET package manager を使用してインストールできます。
$ Install-Package FirebaseAdmin -Version 1.2.1
または、dotnet コマンドライン ユーティリティを使用してインストールします。
$ dotnet add package FirebaseAdmin --version 1.2.1
または、次のパッケージ参照エントリを .csproj ファイルに追加してインストールできます。
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="1.2.1" />
</ItemGroup>
SDK の初期化
Firebase console プロジェクトを作成し、サービス アカウントの認証情報が含まれる JSON ファイルをダウンロードしたら、以下のコード スニペットを使用して SDK を初期化します。
Node.js
var admin = require('firebase-admin');
var serviceAccount = require('path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
Java
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new 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
cred = credentials.Certificate('path/to/serviceAccountKey.json')
default_app = firebase_admin.initialize_app(cred)
Google App Engine スタンダード環境で Python Admin SDK を使用するには、追加の構成がいくつか必要になります。
Go
import (
"context"
"log"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"google.golang.org/api/option"
)
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#
using FirebaseAdmin;
using FirebaseAdmin.Auth;
using Google.Apis.Auth.OAuth2;
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/serviceAccountKey.json"),
});
データベース名は、Firebase コンソール プロジェクトの [データベース] ページにあります。
サービス アカウント ファイルを参照できない場合は、サービス アカウントの個々のフィールドを Admin Node.js SDK にインラインで渡すことができます。
Node.js
admin.initializeApp({
credential: admin.credential.cert({
projectId: '<PROJECT_ID>',
clientEmail: 'foo@<PROJECT_ID>.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
}),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
あるいは、別の種類の認証情報を使用して Admin SDK を認証することもできます。たとえば、Google Cloud Platform 内でコードを実行する場合は、Google アプリケーションのデフォルトの認証情報を使用すると、Admin SDK 自体がサービス アカウントをフェッチします。
Node.js
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
Java
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);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(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
Realtime Database または Authentication 用の Google アプリケーションのデフォルト認証情報を使用する Google Compute Engine VM を使用している場合は、適切なアクセス スコープも設定する必要があります。Realtime Database および Authentication には、userinfo.email および cloud-platform または firebase.database で終わるスコープが必要です。既存のアクセス スコープを確認して変更するには、gcloud を使用して次のコマンドを実行します。
gcloud
# Check the existing access scopes
gcloud compute instances describe [INSTANCE_NAME] --format json
# The above command returns the service account information. For example:
"serviceAccounts": [
{
"email": "your.gserviceaccount.com",
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email"
]
}
],
# Stop the VM, then run the following command, using the service account
# that gcloud returned when you checked the scopes.
gcloud compute instances set-service-account [INSTANCE_NAME] --service-account "your.gserviceaccount.com" --scopes "https://www.googleapis.com/auth/firebase.database,https://www.googleapis.com/auth/userinfo.email"
また、次に示すように、Google OAuth2 更新トークンを使った認証を可能にする認証情報も Admin SDK に備わっています。
Node.js
var refreshToken; // Get refresh token from OAuth2 flow
admin.initializeApp({
credential: admin.credential.refreshToken(refreshToken),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
Java
FileInputStream refreshToken = new FileInputStream("path/to/refreshToken.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(refreshToken))
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);Python
cred = credentials.RefreshToken('path/to/refreshToken.json')
default_app = firebase_admin.initialize_app(cred)Go
opt := option.WithCredentialsFile("path/to/refreshToken.json")
config := &firebase.Config{ProjectID: "my-project-id"}
app, err := firebase.NewApp(context.Background(), config, opt)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
C#
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/refreshToken.json"),
});
SDK はパラメータなしで初期化することもできます。この場合、SDK は Google アプリケーションのデフォルト認証情報を使用し、FIREBASE_CONFIG 環境変数からオプションを読み取ります。FIREBASE_CONFIG 変数のコンテンツが { で始まる場合は、JSON オブジェクトとして解析されます。それ以外の場合、SDK は文字列がオプションを含む JSON ファイルの名前であるとみなします。
Node.js
// Initialize the default app
var admin = require('firebase-admin');
var app = admin.initializeApp();
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();
これで、Firebase Admin SDK を使用して次のタスクを行う準備が整いました。
- カスタム認証の実装
- Firebase Authentication ユーザーの管理
- Realtime Database からのデータの読み取りと書き込み
- Firebase Cloud Messaging メッセージの送信
複数のアプリを初期化する
ほとんどの場合、単一の(デフォルトの)アプリを初期化するだけで済みます。そのアプリからは 2 つの方法でサービスにアクセスできます(この 2 つの方法は同等です)。
Node.js
// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);
console.log(defaultApp.name); // '[DEFAULT]'
// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();
// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();
Java
// Initialize the default app
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);
System.out.println(defaultApp.getName()); // "[DEFAULT]"
// Retrieve services by passing the defaultApp variable...
FirebaseAuth defaultAuth = FirebaseAuth.getInstance(defaultApp);
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);
// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.getInstance();
defaultDatabase = FirebaseDatabase.getInstance();Python
# Import the Firebase service
from firebase_admin import auth
# Initialize the default app
default_app = firebase_admin.initialize_app(cred)
print(default_app.name) # "[DEFAULT]"
# Retrieve services via the auth package...
# auth.create_custom_token(...)Go
// Initialize default app
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
// Access auth service from the default app
client, err := app.Auth(context.Background())
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
C#
// Initialize the default app
var defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
Console.WriteLine(defaultApp.Name); // "[DEFAULT]"
// Retrieve services by passing the defaultApp variable...
var defaultAuth = FirebaseAuth.GetAuth(defaultApp);
// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.DefaultInstance;
ユースケースによっては、複数のアプリを同時に作成することが必要になる場合があります。たとえば、1 つの Firebase プロジェクトの Realtime Database のデータを読み取り、別のプロジェクト用のカスタム トークンを作成することがあります。あるいは、別々の認証情報を使って 2 つのアプリを認証すべき場合もあります。Firebase SDK では、それぞれ独自の構成情報を使用して複数のアプリを同時に作成できます。
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();
var defaultDatabase = admin.database();
// Use the otherApp variable to retrieve the other app's services
var otherAuth = otherApp.auth();
var otherDatabase = otherApp.database();
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);
次のステップ
以下で Firebase の詳細を確認します。
- Firebase アプリのサンプルを確認する。
- GitHub で Node.js、Java、Python のオープンソース コードを確認する。
Firebase 機能をアプリに追加します。
- Cloud Functions でサーバーレス バックエンドを作成する。
- Realtime Database で情報を保存するか、Cloud Storage で blob データを保存する。
- Cloud Messaging を使用して通知を受け取る。

