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:
Consola
-
Create a service account:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator
). Learn how to grant roles. -
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.
-
Ensure that you have the Create Service Accounts IAM role
(
-
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:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator
). Learn how to grant roles. -
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
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 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
-
Ensure that you have the Create Service Accounts IAM role
(
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?
- Veja o código fonte e a documentação adicional do SDK Admin no GitHub:
- Migre os utilizadores existentes para a Identity Platform
- Faça a gestão de fornecedores SAML e OIDC através de programação
- Faça a gestão de inquilinos da Identity Platform