Admin SDK installieren

In diesem Dokument wird gezeigt, wie Sie das Identity Platform Admin SDK installieren. Mit dem Admin SDK können Sie Identity Platform über eine Serverumgebung verwalten und Administratoraktionen wie die Migration von Nutzern, das Festlegen benutzerdefinierter Anforderungen und das Konfigurieren von Identitätsanbietern ausführen.

Hinweise

Zur Verwendung des Admin SDK benötigen Sie eine Server-App, auf der eine der folgenden Optionen ausgeführt wird:

Sprache Framework-Mindestversion
Node.js Node.js 8.13.0 oder höher
Java Java 7 oder höher (Java 8 oder höher empfohlen)
Python Python 2.7 oder höher oder 3.4 oder höher (3.4 oder höher wird empfohlen)
Einfach loslegen (Go) Go 1.9 oder höher
C# .NET Framework 4.5 oder höher oder .NET Core 1.5 oder höher

In der folgenden Tabelle sind die Features aufgeführt, die von den einzelnen SDK-Sprachen unterstützt werden:

Funktion Node.js Java Python Einfach loslegen (Go) C#
Benutzerdefinierte Tokenerstellung
Bestätigung per Ausweis
Nutzerverwaltung
Zugriffskontrolle mit benutzerdefinierten Ansprüchen
Widerruf von Aktualisierungstokens
Nutzer importieren
Verwaltung von Sitzungscookies
E-Mail-Aktionslinks generieren
SAML-/OIDC-Anbieterkonfigurationen verwalten
Unterstützung für Mehrmandantenfähigkeit
Echtzeitdatenbank *
Firebase Cloud Messaging
FCM-Multicast
Abos für FCM-Themen verwalten
Cloud Storage
Firestore
Projektmanagement
Sicherheitsregeln
Verwaltung von ML-Modellen
Firebase Remote Config
Firebase App Check
Firebase Extensions

Außerdem benötigen Sie ein Dienstkonto und einen Schlüssel für Ihr Projekt:

Console

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

Geben Sie die Anmeldedaten zur Authentifizierung für Ihren Anwendungscode durch Festlegung der Umgebungsvariable GOOGLE_APPLICATION_CREDENTIALS an. Diese Variable gilt nur für Ihre aktuelle Shellsitzung. Wenn Sie möchten, dass die Variable für zukünftige Shell-Sitzungen gilt, legen Sie die Variable in Ihrer Shell-Startdatei fest, z. B. in der Datei ~/.bashrc oder ~/.profile.

Linux oder macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Geben Sie für KEY_PATH den Dateipfad der JSON-Datei an, die Ihre Anmeldedaten enthält.

Beispiel:

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

Windows

Für PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Geben Sie für KEY_PATH den Dateipfad der JSON-Datei an, die Ihre Anmeldedaten enthält.

Beispiel:

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

Für Eingabeaufforderung:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Geben Sie für KEY_PATH den Dateipfad der JSON-Datei an, die Ihre Anmeldedaten enthält.

SDK installieren

Node.js

Das Node.js Admin SDK ist auf npm verfügbar. Wenn Sie noch keine package.json-Datei haben, erstellen Sie eine mit npm init. Installieren Sie als Nächstes das npm-Paket und speichern Sie es in Ihrem package.json:

npm install firebase-admin --save

Wenn Sie das Modul in Ihrer Anwendung verwenden möchten, require Sie es über eine beliebige JavaScript-Datei:

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

Wenn Sie ES2015 verwenden, können Sie stattdessen das Modul import löschen:

import * as admin from 'firebase-admin';

Java

Das Java Admin SDK wird im zentralen Maven-Repository veröffentlicht. Um die Bibliothek zu installieren, müssen Sie sie als Abhängigkeit in Ihrer build.gradle-Datei deklarieren:

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

Wenn Sie die Anwendung mit Maven erstellen, können Sie Ihrer pom.xml die folgende Abhängigkeit hinzufügen:

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

Python

Das Python Admin SDK ist mit pip verfügbar.

pip install --user firebase-admin

Einfach loslegen (Go)

Verwenden Sie das Dienstprogramm go get, um das Go Admin SDK zu installieren:

go get firebase.google.com/go

C#

Installieren Sie das .NET Admin SDK mithilfe des .NET-Paketmanagers:

Install-Package FirebaseAdmin -Version 1.9.1

Alternativ können Sie es mit dem dotnet-Befehlszeilentool installieren:

dotnet add package FirebaseAdmin --version 1.9.1

Sie können es auch installieren, indem Sie der Datei .csproj den folgenden Paketverweis hinzufügen:

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

SDK mit Standardanmeldedaten initialisieren

Fügen Sie der Serveranwendung den folgenden Code hinzu, um das Admin SDK mit den Standardanmeldedaten zu initialisieren:

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

Einfach loslegen (Go)

app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

C#

FirebaseApp.Create();

SDK mit einer Dienstkontoschlüsseldatei initialisieren

Sie können auch manuell eine Dienstkonto-Schlüsseldatei angeben:

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)

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

Mehrere Anwendungen initialisieren

Normalerweise möchten Sie nur eine einzelne Standardanwendung initialisieren. Sie können jedoch auch mehrere Anwendungsinstanzen mit jeweils eigenen Konfigurationsoptionen und Authentifizierungsstatus erstellen.

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)

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

Bereiche festlegen

Wenn Sie eine Compute Engine-VM mit Standardanmeldedaten für Google-Anwendungen für die Authentifizierung verwenden, müssen Sie die richtigen Zugriffsbereiche festlegen. Identity Platform benötigt die Zugriffsbereiche userinfo.email und cloud-platform.

Führen Sie folgenden Befehl aus, um Ihre vorhandenen Zugriffsbereiche zu prüfen:

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

Der Befehl gibt Informationen zum Dienstkonto zurück. Beispiel:

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

Um Zugriffsbereiche zu aktualisieren, halten Sie die VM an und führen Sie dann Folgendes aus:


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"

Nächste Schritte