Installazione dell'SDK Admin

Questo documento mostra come installare l'SDK Admin di Identity Platform. L'SDK Admin ti consente di gestire Identity Platform da un ambiente server ed eseguire azioni amministrative come la migrazione degli utenti, l'impostazione di rivendicazioni personalizzate e la configurazione dei provider di identità.

Prima di iniziare

Per utilizzare l'SDK Admin, devi disporre di un'app server che esegue una delle seguenti operazioni:

Lingua Versione minima del framework
Node.js Node.js 8.13.0 o versioni successive
Java Java 7+ (Java 8+ consigliato)
Python Python 2.7+ o 3.4+ (3.4+ consigliato)
Vai Go 1.9+
C# .NET Framework 4.5+ o .NET Core 1.5+

La tabella seguente elenca le funzionalità supportate da ogni lingua dell'SDK:

Funzionalità Node.js Java Python Vai C#
Generazione di token personalizzati
Verifica del token ID
Gestione utenti
Controllare l'accesso con rivendicazioni personalizzate
Revoca del token di aggiornamento
Importa utenti
Gestione dei cookie di sessione
Generazione di link di azioni email
Gestione delle configurazioni dei provider SAML/OIDC
Supporto multi-tenant
Realtime Database *
Firebase Cloud Messaging
FCM Multicast
Gestire le iscrizioni agli argomenti FCM
Cloud Storage
Firestore
Project management
Regole di sicurezza
Gestione dei modelli ML
Firebase Remote Config
Firebase App Check
Firebase Extensions

Inoltre, devi disporre di un account di servizio e di una chiave per il tuo progetto:

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

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 o 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.

Installazione dell'SDK

Node.js

L'SDK Admin per Node.js è disponibile su npm. Se non hai già un file package.json, creane uno utilizzando npm init. Poi, installa il pacchetto npm e salvalo in package.json:

npm install firebase-admin --save

Per utilizzare il modulo nella tua app, require da qualsiasi file JavaScript:

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

Se utilizzi ES2015, puoi import il modulo:

import * as admin from 'firebase-admin';

Java

L'SDK Java Admin è pubblicato nel repository centrale Maven. Per installare la libreria, dichiarala come dipendenza nel file build.gradle:

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

Se utilizzi Maven per creare la tua app, puoi aggiungere la seguente dipendenza al file pom.xml:

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

Python

L'SDK Python Admin è disponibile tramite pip.

pip install --user firebase-admin

Vai

Utilizza l'utilità go get per installare l'SDK Admin di Go:

go get firebase.google.com/go

C#

Installa l'SDK Admin .NET utilizzando il gestore di pacchetti .NET:

Install-Package FirebaseAdmin -Version 1.9.1

In alternativa, installalo utilizzando l'utilità a riga di comando dotnet:

dotnet add package FirebaseAdmin --version 1.9.1

In alternativa, puoi installarlo aggiungendo la seguente voce di riferimento del pacchetto al file .csproj:

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

Inizializzazione dell'SDK utilizzando le credenziali predefinite

Aggiungi il seguente codice all'app server per inizializzare l'SDK Admin utilizzando le credenziali predefinite:

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

Vai

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

C#

FirebaseApp.Create();

Inizializzazione dell'SDK con un file di chiave del account di servizio

Puoi anche specificare manualmente un file della chiave del account di servizio:

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)

Vai

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

Inizializzazione di più app

In genere, ti consigliamo di inizializzare una sola app predefinita. Tuttavia, puoi anche creare più istanze dell'app, ognuna con le proprie opzioni di configurazione e stato di autenticazione.

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)

Vai

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

Impostazione degli ambiti

Se utilizzi una VM di Compute Engine con le Credenziali predefinite dell'applicazione Google per l'autenticazione, devi impostare gli ambiti di accesso corretti. Identity Platform richiede gli ambiti di accesso userinfo.email e cloud-platform.

Per controllare gli ambiti di accesso esistenti, esegui questo comando:

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

Il comando restituirà informazioni sul account di servizio. Ad esempio:

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

Per aggiornare gli ambiti di accesso, arresta la VM, quindi esegui il seguente comando:


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"

Passaggi successivi