Instalar el SDK Admin

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

Antes de empezar

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

Idioma Versión mínima del framework
Node.js Node.js 8.13.0 o versiones posteriores
Java Java 7 o versiones posteriores (se recomienda Java 8 o versiones posteriores)
Python Python 2.7 o 3.4 (se recomienda 3.4 o una versión posterior)
Go Go 1.9 y versiones posteriores
C# .NET Framework 4.5 o una versión posterior, o .NET Core 1.5 o una versión posterior

En la siguiente tabla se indican las funciones compatibles con cada idioma del SDK:

Función Node.js Java Python Go C#
Creación de tokens personalizados
Verificación de tokens de ID
Gestión de usuarios
Controlar el acceso con reclamaciones personalizadas
Revocación de tokens de actualización
Importar usuarios
Gestión de cookies de sesión
Generar enlaces de acción de correo
Gestionar configuraciones de proveedores de SAML y OIDC
Compatibilidad con multitenancy
Realtime Database *
Firebase Cloud Messaging
Multicast de FCM
Gestionar suscripciones a temas de FCM
Cloud Storage
Firestore
Gestión de proyectos
Reglas de seguridad
Gestión de modelos de aprendizaje automático
Firebase Remote Config
Comprobación de Aplicaciones de Firebase
Extensiones de Firebase

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

Consola

Create a service account:

  1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator). Learn how to grant roles.
  2. In the Google Cloud console, go to the Create service account page.

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

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

  7. Click Continue.
  8. 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

Create a service account:

  1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator). Learn how to grant roles.
  2. In the Google Cloud console, go to the Create service account page.

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

  5. Click Create and continue.
  6. Grant the Project > Admin role to the service account.

    To grant the role, find the Select a role list, then select Project > Admin.

  7. Click Continue.
  8. 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.

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.

Instalar el SDK

Node.js

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

npm install firebase-admin --save

Para usar el módulo en tu aplicación, require desde cualquier archivo JavaScript:

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

Si usas ES2015, puedes import el módulo:

import * as admin from 'firebase-admin';

Java

El SDK de administrador de Java se publica en el repositorio central de Maven. Para instalar la biblioteca, declárala como dependencia en el archivo build.gradle:

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

Si usas Maven para compilar tu aplicación, puedes añadir la siguiente dependencia a tu pom.xml:

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

Python

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

pip install --user firebase-admin

Go

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

go get firebase.google.com/go

C#

Instala el SDK de administrador de .NET con el gestor de paquetes de .NET:

Install-Package FirebaseAdmin -Version 1.9.1

También puedes instalarlo con la utilidad de línea de comandos dotnet:

dotnet add package FirebaseAdmin --version 1.9.1

También puedes instalarlo añadiendo la siguiente entrada de referencia de paquete a tu archivo .csproj:

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

Inicializar el SDK con las credenciales predeterminadas

Añade el siguiente código a tu aplicación de servidor para inicializar el SDK de administrador con 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();

Inicializar el SDK con un archivo de clave de cuenta de servicio

También puedes especificar manualmente un archivo de clave de cuenta de servicio:

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

Inicializar varias aplicaciones

Normalmente, solo querrás inicializar una aplicación predeterminada. Sin embargo, también puedes crear varias instancias de la aplicación, cada una con sus propias opciones de configuración y 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);

Definir ámbitos

Si utilizas una VM de Compute Engine con las credenciales predeterminadas de la aplicación de Google para la autenticación, tendrás que definir los ámbitos de acceso adecuados. Identity Platform requiere los ámbitos de acceso userinfo.email y cloud-platform.

Para comprobar los ámbitos de acceso que ya tienes, ejecuta lo siguiente:

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

El comando devolverá 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 ámbitos de acceso, detén la VM y, a continuación, ejecuta lo siguiente:


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"

Siguientes pasos