Instalar o SDK Admin

Este documento mostra como instalar o Admin SDK da Identity Platform. O SDK Admin permite-lhe gerir a Identity Platform a partir de um ambiente de servidor e realizar ações de administrador, como migrar utilizadores, definir reivindicações personalizadas e configurar fornecedores de identidade.

Antes de começar

Para usar o SDK de administrador, precisa de uma app de servidor que execute um dos seguintes sistemas:

Idioma Versão mínima do framework
Node.js Node.js 8.13.0 e superior
Java Java 7 ou superior (Java 8 ou superior recomendado)
Python Python 2.7 ou 3.4 ou superior (recomenda-se 3.4 ou superior)
Ir Go 1.9+
C# .NET Framework 4.5 ou superior ou .NET Core 1.5 ou superior

A tabela seguinte apresenta as funcionalidades suportadas por cada idioma do SDK:

Funcionalidade Node.js Java Python Ir C#
Geração de tokens personalizados
Validação de token de ID
Gestão de utilizadores
Controle o acesso com reivindicações personalizadas
Revogação do token de atualização
Importe utilizadores
Gestão de cookies de sessão
Gerar links de ações de email
Gerir configurações de fornecedores SAML/OIDC
Suporte multi-inquilino
Realtime Database *
Firebase Cloud Messaging
FCM Multicast
Faça a gestão das subscrições de tópicos do FCM
Cloud Storage
Firestore
Gestão de projetos
Regras de segurança
Gestão de modelos de ML
Firebase Remote Config
Firebase App Check
Firebase Extensions

Consola

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

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

  1. Set up authentication:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator). Learn how to grant roles.
    2. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    3. Grant the roles/identitytoolkit.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=roles/identitytoolkit.admin

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
    4. 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

Instalar o SDK

Node.js

O SDK de administrador do Node.js está disponível no npm. Se ainda não tiver um ficheiro package.json, crie um com o npm init. Em seguida, instale o pacote npm e guarde-o em package.json:

npm install firebase-admin --save

Para usar o módulo na sua app, require-o a partir de qualquer ficheiro JavaScript:

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

Se estiver a usar ES2015, pode import o módulo em alternativa:

import * as admin from 'firebase-admin';

Java

O SDK de administração Java é publicado no repositório central do Maven. Para instalar a biblioteca, declare-a como uma dependência no ficheiro build.gradle:

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

Se usar o Maven para criar a sua app, pode adicionar a seguinte dependência ao seu pom.xml:

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

Python

O SDK de administrador do Python está disponível através do pip.

pip install --user firebase-admin

Ir

Use o utilitário go get para instalar o SDK de administrador do Go:

go get firebase.google.com/go

C#

Instale o SDK de administrador do .NET através do gestor de pacotes do .NET:

Install-Package FirebaseAdmin -Version 1.9.1

Em alternativa, instale-o através do utilitário de linha de comandos dotnet:

dotnet add package FirebaseAdmin --version 1.9.1

Em alternativa, pode instalá-lo adicionando a seguinte entrada de referência do pacote ao ficheiro .csproj:

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

Inicializar o SDK com credenciais predefinidas

Adicione o seguinte código à sua app de servidor para inicializar o SDK Admin com as credenciais predefinidas:

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

Ir

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

C#

FirebaseApp.Create();

Inicializar o SDK com um ficheiro de chave de conta de serviço

Também pode especificar manualmente um ficheiro de chave de conta de serviço:

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)

Ir

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 várias apps

Normalmente, só quer inicializar uma única app predefinida. No entanto, também pode criar várias instâncias da app, cada uma com as suas próprias opções de configuração e estado de autenticação.

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)

Ir

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

Se estiver a usar uma VM do Compute Engine com as Credenciais predefinidas da aplicação Google para autenticação, tem de definir os âmbitos de acesso corretos. A Identity Platform requer os âmbitos de acesso userinfo.email e cloud-platform.

Para verificar os âmbitos de acesso existentes, execute o seguinte:

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

O comando devolve informações sobre a conta de serviço. Por exemplo:

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

Para atualizar os âmbitos de acesso, pare a VM e, em seguida, execute o seguinte:


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"

O que se segue?