Installazione dell'SDK Admin
Questo documento mostra come installare l'SDK Admin di Identity Platform. L'SDK Admin consente di gestire Identity Platform da un ambiente server ed eseguire azioni dell'amministratore come la migrazione degli utenti, l'impostazione di attestazioni personalizzate e la configurazione dei provider di identità.
Prima di iniziare
Per utilizzare SDK Admin, è necessaria un'app server che esegua una delle seguenti operazioni:
Lingua | Versione minima del framework |
---|---|
Node.js | Node.js 8.13.0 o versioni successive |
Java | Java 7+ (è consigliato Java 8+) |
Python | Python 2.7+ o 3.4+ (consigliato 3.4+) |
Go | Passa a 1.9 o versioni successive |
C# | .NET Framework 4.5+ o .NET Core 1.5+ |
Nella tabella seguente sono elencate le funzionalità supportate da ogni linguaggio dell'SDK:
Inoltre, per il tuo progetto sono necessari un account di servizio e una chiave:
Console
Create a service account:
-
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
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
. - Click Create and continue.
-
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.
- Click Continue.
-
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:
- In the Google Cloud console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, and then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
gcloud
Set up authentication:
-
Create the service account:
gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
Replace
SERVICE_ACCOUNT_NAME
with a name for the service account. -
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 accountPROJECT_ID
: the project ID where you created the service account
-
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 fileSERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service account
Fornisci le credenziali di autenticazione al codice dell'applicazione impostando la variabile di ambiente GOOGLE_APPLICATION_CREDENTIALS
. Questa variabile si applica solo alla sessione di shell attuale. Se vuoi che la variabile venga applicata a future sessioni shell, impostala nel file di avvio della shell, ad esempio nel file ~/.bashrc
o ~/.profile
.
Linux o macOS
export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH
"
Sostituisci KEY_PATH
con il percorso del file JSON che contiene le tue credenziali.
Ad esempio:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
Windows
Per PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH
"
Sostituisci KEY_PATH
con il percorso del file JSON che contiene le tue credenziali.
Ad esempio:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
Per il prompt dei comandi:
set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
Sostituisci KEY_PATH
con il percorso del file JSON che contiene le tue credenziali.
Installazione dell'SDK
Node.js
L'SDK Admin di Node.js è disponibile su npm. Se non hai ancora un file package.json
, creane uno utilizzando npm init
. Installa il pacchetto npm e salvalo su 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 invece 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 a pom.xml
:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.11.0</version>
</dependency>
Python
L'SDK Admin Python è disponibile utilizzando pip.
pip install --user firebase-admin
Go
Utilizza l'utilità go get
per installare l'SDK Go Admin:
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, installala utilizzando l'utilità a riga di comando dotnet
:
dotnet add package FirebaseAdmin --version 1.9.1
In alternativa, puoi installarlo aggiungendo al tuo file .csproj
la seguente voce di riferimento del pacchetto:
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="1.9.1" />
</ItemGroup>
Inizializzazione dell'SDK utilizzando le credenziali predefinite
Aggiungi il codice seguente 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()
Go
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 chiavi dell'account di servizio
Puoi anche specificare manualmente un file di chiavi per l'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)
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"), });
Inizializzazione di più app
In genere, è consigliabile inizializzare una singola app predefinita. Tuttavia, puoi anche creare più istanze di app, ciascuna con le proprie opzioni di configurazione e il proprio 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)
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);
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 sull'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 ed esegui questo 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
- Visualizza il codice sorgente e la documentazione aggiuntiva per SDK Admin su GitHub:
- Eseguire la migrazione degli utenti esistenti a Identity Platform
- Gestire i provider SAML e OIDC in modo programmatico
- Gestisci i tenant di Identity Platform