Como instalar o SDK Admin
Veja neste documento como instalar o SDK Admin do Identity Platform. Com o SDK Admin, você gerencia o Identity Platform de um ambiente de servidor e realiza ações de administrador, como migrar usuários, definir declarações personalizadas e configurar provedores de identidade.
Antes de começar
Para usar o SDK Admin, você precisa de um app de servidor que execute um dos seguintes procedimentos:
Idioma | Versão mínima do framework |
---|---|
Node.js | Node.js 8.13.0+ |
Java | Java 7+ (Java 8+ recomendado) |
Python | Python 2.7+ ou 3.4+ (3.4+ recomendado) |
Go | Go 1.9+ |
C# | .NET Framework 4.5+ ou .NET Core 1.5+ |
A tabela a seguir lista os recursos compatíveis com cada linguagem de SDK:
Além disso, você precisará de uma conta de serviço e uma chave para seu projeto:
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
Forneça credenciais de autenticação ao código do aplicativo
definindo a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS
. Essa
variável se aplica somente à sessão de shell atual. Se você quiser que a variável
seja aplicada em sessões de shell futuras, defina a variável no arquivo de inicialização de shell,
por exemplo, no arquivo ~/.bashrc
ou ~/.profile
.
Linux ou macOS
export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH
"
Substitua KEY_PATH
pelo caminho do arquivo JSON que contém suas credenciais.
Exemplo:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
Windows
Para PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH
"
Substitua KEY_PATH
pelo caminho do arquivo JSON que contém suas credenciais.
Exemplo:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
Para prompt de comando:
set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
Substitua KEY_PATH
pelo caminho do arquivo JSON que contém suas credenciais.
Como instalar o SDK
Node.js
O SDK Admin para Node.js está disponível em npm. Se você ainda não
tiver um arquivo package.json
, crie um usando npm init
. Em seguida, instale o
pacote npm e salve-o no package.json
:
npm install firebase-admin --save
Para usar o módulo no seu app, require
em qualquer arquivo JavaScript:
var admin = require('firebase-admin');
Se você estiver usando ES2015, use import
no módulo:
import * as admin from 'firebase-admin';
Java
O SDK Admin para Java é publicado no repositório Maven central.
Para instalar a biblioteca, declare-a como uma dependência no seu arquivo
build.gradle
:
dependencies {
implementation 'com.google.firebase:firebase-admin:6.11.0'
}
Se você usa o Maven para criar seu aplicativo, adicione esta
dependência ao pom.xml
:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.11.0</version>
</dependency>
Python
O SDK Admin para Python está disponível usando pip.
pip install --user firebase-admin
Go
Use o utilitário go get
para instalar o SDK Admin do Go:
go get firebase.google.com/go
C#
Instale o SDK Admin do .NET usando o gerenciador de pacotes .NET:
Install-Package FirebaseAdmin -Version 1.9.1
Como alternativa, instale-o usando o utilitário de linha de comando dotnet
:
dotnet add package FirebaseAdmin --version 1.9.1
Ou você pode instalá-lo adicionando a seguinte entrada de referência do pacote
ao seu arquivo .csproj
:
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="1.9.1" />
</ItemGroup>
Como inicializar o SDK usando credenciais padrão
Adicione o seguinte código ao app de servidor para inicializar o SDK Admin usando as credenciais padrão:
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();
Como inicializar o SDK com um arquivo de chave da conta de serviço
Também é possível especificar manualmente um arquivo de chave da 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)
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"), });
Como inicializar vários aplicativos
Normalmente, você só precisará inicializar um único app padrão. No entanto, também é possível criar várias instâncias de aplicativos, cada uma com as 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)
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);
Como definir escopos
Se estiver usando uma VM do Compute Engine com o Application Default Credentials
do Google para autenticação, você precisará definir os
escopos de acesso corretos.
O Identity Platform requer os escopos de acesso
userinfo.email
e cloud-platform
.
Para verificar os escopos de acesso atuais, execute o comando a seguir:
gcloud compute instances describe [INSTANCE-NAME] --format json
O comando retornará informações sobre a conta de serviço. Exemplo:
"serviceAccounts": [
{
"email": "example.gserviceaccount.com",
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email"
]
}
]
Para atualizar os escopos de acesso, interrompa a VM e 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"
A seguir
- Veja o código-fonte e a documentação extra do SDK Admin no GitHub:
- Migrar usuários atuais para o Identity Platform
- Gerenciar provedores SAML e OIDC de maneira programática
- Gerenciar locatários do Identity Platform