Menginstal Admin SDK

Dokumen ini menunjukkan cara menginstal Identity Platform Admin SDK. Admin SDK memungkinkan Anda mengelola Identity Platform dari lingkungan server, dan melakukan tindakan administrator seperti memigrasikan pengguna, menetapkan klaim kustom, dan mengonfigurasi penyedia identitas.

Sebelum memulai

Untuk menggunakan Admin SDK, Anda memerlukan aplikasi server yang menjalankan salah satu dari berikut:

Bahasa Versi framework minimum
Node.js Node.js 8.13.0+
Java Java 7+ (Java 8+ direkomendasikan)
Python Python 2.7+ atau 3.4+ (direkomendasikan 3.4+)
Go Go 1.9+
C# .NET Framework 4.5+ atau .NET Core 1.5+

Tabel berikut mencantumkan fitur yang didukung oleh setiap bahasa SDK:

Fitur Node.js Java Python Go C#
Pembuatan token kustom
Verifikasi token ID
Pengelolaan pengguna
Mengontrol akses dengan klaim kustom
Pencabutan token refresh
Mengimpor pengguna
Pengelolaan cookie sesi
Membuat link tindakan email
Mengelola konfigurasi penyedia SAML/OIDC
Dukungan multi-tenancy
Realtime Database *
Firebase Cloud Messaging
FCM Multicast
Mengelola langganan topik FCM
Cloud Storage
Firestore
Pengelolaan Proyek
Aturan keamanan
Pengelolaan model ML
Firebase Remote Config
Firebase App Check
Firebase Extensions

Selain itu, Anda memerlukan akun layanan dan kunci untuk project Anda:

Konsol

Create a service account:

  1. In the Google Cloud console, go to the Create service account page.

    Go to Create service account
  2. Select your project.
  3. 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.

  4. Click Create and continue.
  5. 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.

  6. Click Continue.
  7. 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:

  1. In the Google Cloud console, click the email address for the service account that you created.
  2. Click Keys.
  3. Click Add key, and then click Create new key.
  4. Click Create. A JSON key file is downloaded to your computer.
  5. Click Close.

gcloud

Set up authentication:

  1. Create the service account:

    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

    Replace SERVICE_ACCOUNT_NAME with a name for the service account.

  2. 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 account
    • PROJECT_ID: the project ID where you created the service account
  3. 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 file
    • SERVICE_ACCOUNT_NAME: the name of the service account
    • PROJECT_ID: the project ID where you created the service account

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. This variable applies only to your current shell session. If you want the variable to apply to future shell sessions, set the variable in your shell startup file, for example in the ~/.bashrc or ~/.profile file.

Linux atau macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

For PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

For command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Replace KEY_PATH with the path of the JSON file that contains your credentials.

Menginstal SDK

Node.js

Node.js Admin SDK tersedia di npm. Jika Anda belum memiliki file package.json, buat file tersebut menggunakan npm init. Selanjutnya, instal paket npm dan simpan ke package.json Anda:

npm install firebase-admin --save

Untuk menggunakan modul tersebut di aplikasi Anda, terapkan require padanya dari file JavaScript apa pun:

var admin = require('firebase-admin');

Jika menggunakan ES2015, Anda dapat menerapkan import pada modul tersebut:

import * as admin from 'firebase-admin';

Java

Java Admin SDK dipublikasikan ke repositori pusat Maven. Untuk menginstal library tersebut, deklarasikan sebagai dependensi di file build.gradle Anda:

dependencies {
  implementation 'com.google.firebase:firebase-admin:6.11.0'
}

Jika menggunakan Maven untuk mem-build aplikasi, Anda dapat menambahkan dependensi berikut ke pom.xml:

<dependency>
  <groupId>com.google.firebase</groupId>
  <artifactId>firebase-admin</artifactId>
  <version>6.11.0</version>
</dependency>

Python

Python Admin SDK tersedia menggunakan pip.

pip install --user firebase-admin

Go

Gunakan aplikasi utilitas go get untuk menginstal Go Admin SDK:

go get firebase.google.com/go

C#

Instal .NET Admin SDK menggunakan pengelola paket .NET:

Install-Package FirebaseAdmin -Version 1.9.1

Sebagai alternatif, Anda dapat menginstalnya menggunakan aplikasi utilitas command line dotnet:

dotnet add package FirebaseAdmin --version 1.9.1

Atau, Anda dapat menginstalnya dengan menambahkan entri referensi paket berikut ke file .csproj Anda:

<ItemGroup>
  <PackageReference Include="FirebaseAdmin" Version="1.9.1" />
</ItemGroup>

Menginisialisasi SDK menggunakan kredensial default

Tambahkan kode berikut ke aplikasi server Anda untuk melakukan inisialisasi Admin SDK menggunakan kredensial default:

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();

Menginisialisasi SDK dengan file kunci akun layanan

Anda juga dapat menentukan file kunci akun layanan secara manual:

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"),
});

Melakukan inisialisasi beberapa aplikasi

Biasanya, Anda hanya ingin menginisialisasi satu aplikasi default. Namun, Anda juga dapat membuat beberapa instance aplikasi, masing-masing dengan opsi konfigurasi dan status autentikasi sendiri.

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);

Menetapkan cakupan

Jika menggunakan VM Compute Engine dengan Kredensial Default Aplikasi Google untuk autentikasi, Anda harus menetapkan cakupan akses yang tepat. Identity Platform memerlukan cakupan akses userinfo.email dan cloud-platform.

Untuk memeriksa cakupan akses yang ada, jalankan perintah berikut:

gcloud compute instances describe [INSTANCE-NAME] --format json

Perintah ini akan menampilkan informasi tentang akun layanan. Contoh:

"serviceAccounts": [
 {
  "email": "example.gserviceaccount.com",
  "scopes": [
   "https://www.googleapis.com/auth/cloud-platform",
   "https://www.googleapis.com/auth/userinfo.email"
   ]
  }
]

Untuk memperbarui cakupan akses, hentikan VM, lalu jalankan perintah berikut:


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"

Langkah selanjutnya