Add the Firebase Admin SDK to Your Server

The Admin SDK lets you interact with Firebase from privileged environments to perform actions like:

  • Read and write Realtime Database data with full admin privileges.
  • Programmatically send Firebase Cloud Messaging messages using a simple, alternative approach to the FCM server protocols.
  • Generate and verify Firebase auth tokens.
  • Access Google Cloud Platform resources like Cloud Storage buckets and Firestore databases associated with your Firebase projects.
  • Create your own simplified admin console to do things like look up user data or change a user's email address for authentication.

If you are interested in using the Node.js SDK as a client for end-user access (for example, in a Node.js desktop or IoT application), as opposed to admin access from a privileged environment (like a server), you should instead follow the instructions for setting up the client JavaScript SDK.

Here is a feature matrix showing what Firebase features are supported in each language:

Feature Node.js Java Python Go C#
Custom Token Minting
ID Token Verification
User Management
Control Access With Custom Claims
Refresh Token Revocation
Import Users
Session Cookie Management
Generating Email Action Links
Realtime Database *
Cloud Messaging
Manage Topic Subscriptions
Cloud Storage
Cloud Firestore
Project Management

To learn more about Admin SDK integration for these uses, see the corresponding Realtime Database, FCM, Authentication, and Cloud Storage documentation. The rest of this page focuses on basic setup for the Admin SDK.

Prerequisites

Before you begin, make sure you have the following:

  • If using the Admin Node.js SDK, a server running Node.js 6.0+
  • If using the Admin Java SDK, a server running Java 7+
  • If using the Admin Python SDK, a server running Python 2.7+ or 3.x
  • If using the Admin Go SDK, a server running Go 1.9+
  • If using the Admin .NET SDK, a server running .NET Framework 4.5+ or .Net Core 1.5+.
  • A server app

Add Firebase to your app

To use the Firebase Admin SDKs, you'll need a Firebase project, a service account to communicate with the Firebase service, and a configuration file with your service account's credentials.

  1. If you don't already have a Firebase project, add one in the Firebase console. The Add project dialog also gives you the option to add Firebase to an existing Google Cloud Platform project.
  2. Navigate to the Service Accounts tab in your project's settings page.
  3. Click the Generate New Private Key button at the bottom of the Firebase Admin SDK section of the Service Accounts tab.

After you click the button, a JSON file containing your service account's credentials will be downloaded. You'll need this to initialize the SDK in the next step.

This file is only generated once. If you lose or leak the key, you can repeat the instructions above to create a new JSON key for the service account.

Add the SDK

If you are setting up a new project, you need to install the SDK for the language of your choice.

Node.js

The Firebase Admin Node.js SDK is available on npm. If you don't already have a package.json file, create one via npm init. Next, install the firebase-admin npm package and save it to your package.json:

$ npm install firebase-admin --save

To use the module in your application, require it from any JavaScript file:

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

If you are using ES2015, you can import the module instead:

import * as admin from 'firebase-admin';

Java

The Firebase Admin Java SDK is published to the Maven central repository. To install the library, declare it as a dependency in your build.gradle file:

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

If you use Maven to build your application, you can add the following dependency to your pom.xml:

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

Python

The Firebase Admin Python SDK is available via pip. You can install the library for all users via sudo:

$ sudo pip install firebase-admin

Or, you can install the library for just the current user by passing the --user flag:

$ pip install --user firebase-admin

Go

The Go Admin SDK can be installed using the go get utility:

$ go get firebase.google.com/go

C#

The .NET Admin SDK can be installed using the .NET package manager:

$ Install-Package FirebaseAdmin -Version 1.0.0

Alternatively, install it using the dotnet command-line utility:

$ dotnet add package FirebaseAdmin --version 1.0.0

Or, you can install it by adding the following package reference entry to your .csproj file:

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

Initialize the SDK

Once you have created a Firebase console project and downloaded a JSON file with your service account credentials, you can initialize the SDK with this code snippet:

Node.js

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

var serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Java

FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new 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

cred = credentials.Certificate('path/to/serviceAccountKey.json')
default_app = firebase_admin.initialize_app(cred)

To use the Python Admin SDK in the Google App Engine standard environment, you'll need some extra configuration.

Go

import (
	"context"
	"log"

	firebase "firebase.google.com/go"
	"firebase.google.com/go/auth"
	"google.golang.org/api/option"
)

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#

using FirebaseAdmin;
using FirebaseAdmin.Auth;
using Google.Apis.Auth.OAuth2;

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile("path/to/serviceAccountKey.json"),
});

You can find your database name on the Database page of your Firebase console project.

If the service account file cannot be referenced, the Admin Node.js SDK can accept the service account's individual fields inline:

Node.js

admin.initializeApp({
  credential: admin.credential.cert({
    projectId: '<PROJECT_ID>',
    clientEmail: 'foo@<PROJECT_ID>.iam.gserviceaccount.com',
    privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
  }),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

The Admin SDKs can alternatively be authenticated with a different credential type. For example, if you are running your code within Google Cloud Platform, you can make use of Google Application Default Credentials to have the Admin SDKs themselves fetch a service account on your behalf:

Node.js

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Java

FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredentials(GoogleCredentials.getApplicationDefault())
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();

FirebaseApp.initializeApp(options);

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(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
});

If you're using a Google Compute Engine VM with Google Application Default Credentials for Realtime Database or Authentication, make sure to also set the right access scopes. For Realtime Database and Authentication, you need scopes ending in userinfo.email and either cloud-platform or firebase.database. To check the existing access scopes and change them, run the following commands using gcloud.

gcloud

# Check the existing access scopes
gcloud compute instances describe [INSTANCE_NAME] --format json

# The above command returns the service account information. For example:
  "serviceAccounts": [
   {
    "email": "your.gserviceaccount.com",
    "scopes": [
     "https://www.googleapis.com/auth/cloud-platform",
     "https://www.googleapis.com/auth/userinfo.email"
     ]
    }
  ],

# Stop the VM, then run the following command, using the service account
# that gcloud returned when you checked the scopes.

gcloud compute instances set-service-account [INSTANCE_NAME] --service-account "your.gserviceaccount.com" --scopes "https://www.googleapis.com/auth/firebase.database,https://www.googleapis.com/auth/userinfo.email"

The Admin SDKs also provide a credential which allows you to authenticate with a Google OAuth2 refresh token:

Node.js

var refreshToken; // Get refresh token from OAuth2 flow

admin.initializeApp({
  credential: admin.credential.refreshToken(refreshToken),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Java

FileInputStream refreshToken = new FileInputStream("path/to/refreshToken.json");

FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredentials(GoogleCredentials.fromStream(refreshToken))
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();

FirebaseApp.initializeApp(options);

Python

cred = credentials.RefreshToken('path/to/refreshToken.json')
default_app = firebase_admin.initialize_app(cred)

Go

opt := option.WithCredentialsFile("path/to/refreshToken.json")
config := &firebase.Config{ProjectID: "my-project-id"}
app, err := firebase.NewApp(context.Background(), config, opt)
if err != nil {
	log.Fatalf("error initializing app: %v\n", err)
}

C#

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile("path/to/refreshToken.json"),
});

The SDK can also be initialized with no parameters. In this case, the SDK uses Google Application Default Credentials and reads options from the FIREBASE_CONFIG environment variable. If the content of the FIREBASE_CONFIG variable begins with a { it will be parsed as a JSON object. Otherwise the SDK assumes that the string is the name of a JSON file containing the options.

Node.js

// Initialize the default app
var admin = require('firebase-admin');
var app = admin.initializeApp();

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

You are now ready to use the Firebase Admin SDKs to accomplish the following tasks:

Initialize multiple apps

In most cases, you only have to initialize a single, default app. You can access services off of that app in two equivalent ways:

Node.js

// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);

console.log(defaultApp.name);  // '[DEFAULT]'

// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();

// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();

Java

// Initialize the default app
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);

System.out.println(defaultApp.getName());  // "[DEFAULT]"

// Retrieve services by passing the defaultApp variable...
FirebaseAuth defaultAuth = FirebaseAuth.getInstance(defaultApp);
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);

// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.getInstance();
defaultDatabase = FirebaseDatabase.getInstance();

Python

# Import the Firebase service
from firebase_admin import auth

# Initialize the default app
default_app = firebase_admin.initialize_app(cred)
print(default_app.name)  # "[DEFAULT]"

# Retrieve services via the auth package...
# auth.create_custom_token(...)

Go

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

// Access auth service from the default app
client, err := app.Auth(context.Background())
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}

C#

// Initialize the default app
var defaultApp = FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.GetApplicationDefault(),
});
Console.WriteLine(defaultApp.Name); // "[DEFAULT]"

// Retrieve services by passing the defaultApp variable...
var defaultAuth = FirebaseAuth.GetAuth(defaultApp);

// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.DefaultInstance;

Some use cases require you to create multiple apps at the same time. For example, you might want to read data from the Realtime Database of one Firebase project and mint custom tokens for another project. Or you might want to authenticate two apps with separate credentials. The Firebase SDK allows you create multiple apps at the same time, each with their own configuration information.

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();
var defaultDatabase = admin.database();

// Use the otherApp variable to retrieve the other app's services
var otherAuth = otherApp.auth();
var otherDatabase = otherApp.database();

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

Next steps

Learn about Firebase:

Add Firebase features to your app:

Оставить отзыв о...

Текущей странице
Нужна помощь? Обратитесь в службу поддержки.