Instalar el SDK de Admin

En este documento, se muestra cómo instalar el SDK de Admin de Identity Platform. El SDK de Admin te permite administrar Identity Platform desde un entorno del servidor y realizar acciones de administrador, como migrar usuarios, configurar reclamaciones personalizadas y configurar proveedores de identidad.

Antes de comenzar

Para usar el SDK de Admin, necesitas una aplicación del servidor que ejecute uno de los siguientes:

Lenguaje Versión mínima del framework
Node.js Node.js 8.13.0+
Java Java 7+r (se recomienda Java 8 o superior)
Python Python 2.7+ o 3.4+ (se recomienda 3.4+)
Go Go 1.9+
C# .NET Framework 4.5+ o .NET Core 1.5+

En la siguiente tabla, se enumeran las características que admite cada lenguaje de SDK:

Atributo Node.js Java Python Go C#
Creación de tokens personalizados
Verificación del token de ID
Administración de usuarios
Controla el acceso con reclamaciones personalizadas
Actualiza la revocación de tokens
Importa usuarios
Administración de cookies de sesión
Cómo generar vínculos de acción de correo electrónico
Administrar la configuración del proveedor SAML/OIDC
Compatibilidad con la función multiusuario
Realtime Database *
Firebase Cloud Messaging
FCM Multicast
Administra las suscripciones a temas de FCM
Cloud Storage
Firestore
Administración de proyectos
Reglas de seguridad
Administración de modelos de AA
Firebase Remote Config
Verificación de aplicaciones de Firebase
Extensiones de Firebase

Además, necesitarás una cuenta de servicio y una clave para tu proyecto:

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

Configura la variable de entorno GOOGLE_APPLICATION_CREDENTIALS para proporcionar credenciales de autenticación al código de la aplicación. Esta variable solo se aplica a la sesión actual de shell. Si quieres que la variable se aplique a sesiones de shell futuras, configura la variable en tu archivo de inicio de shell, por ejemplo, en el archivo ~/.bashrc o ~/.profile.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta del archivo JSON que contiene tus credenciales.

Por ejemplo:

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

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta del archivo JSON que contiene tus credenciales.

Por ejemplo:

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

Para el símbolo del sistema:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Reemplaza KEY_PATH por la ruta del archivo JSON que contiene tus credenciales.

Instalar el SDK

Node.js

El SDK de Admin de Node.js está disponible en npm. Si aún no tienes un archivo package.json, crea uno mediante npm init. A continuación, instala el paquete de npm y guárdalo en tu package.json:

npm install firebase-admin --save

Para usar el módulo en tu app, usa require desde cualquier archivo de JavaScript:

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

Si usas ES2015, también puedes import el módulo en su lugar:

import * as admin from 'firebase-admin';

Java

El SDK de Admin de Java se publica en el repositorio central de Maven. Para instalar la biblioteca, debes declararla como una dependencia en el archivo build.gradle:

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

Si usas Maven para compilar tu app, puedes agregar la siguiente dependencia a pom.xml:

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

Python

El SDK de Admin de Python está disponible mediante pip.

pip install --user firebase-admin

Go

Usa la utilidad go get para instalar el SDK de Admin de Go:

go get firebase.google.com/go

C#

Instala el SDK de Admin de .NET mediante el administrador de paquetes de .NET:

Install-Package FirebaseAdmin -Version 1.9.1

De manera alternativa, instálalo mediante la utilidad de línea de comandos de dotnet:

dotnet add package FirebaseAdmin --version 1.9.1

O bien, puedes hacerlo si agregas la siguiente entrada de referencia de paquete en el archivo .csproj:

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

Inicializa el SDK mediante credenciales predeterminadas

Agrega el siguiente código a tu app de servidor para inicializar el SDK de Admin mediante las credenciales predeterminadas:

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

Inicializa el SDK con un archivo de claves de la cuenta de servicio

También puedes especificar un archivo de claves de una cuenta de servicio de forma 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"),
});

Inicializa varias aplicaciones

Por lo general, solo querrás inicializar una única app predeterminada. Sin embargo, también puedes crear varias instancias de aplicación, cada una con sus propias opciones de configuración y su propio estado de autenticación.

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

Configura los permisos

Si usas una VM de Compute Engine con las credenciales predeterminadas de la aplicación de Google para la autenticación, deberás establecer los permisos de acceso adecuados. Identity Platform requiere los permisos de acceso userinfo.email y cloud-platform.

Para verificar los permisos de acceso existentes, ejecuta el siguiente comando:

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

El comando mostrará información sobre la cuenta de servicio. Por ejemplo:

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

Para actualizar los permisos de acceso, detén la VM y, luego, ejecuta el siguiente 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"

¿Qué sigue?