Аутентификация запросов REST

The Firebase SDKs handle all authentication and communication with the Firebase Realtime Database on your behalf. However, when you're in an environment that doesn't have a client SDK or you want to avoid the overhead of a persistent database connection, you can make use of the Realtime Database REST API to read and write data.

Аутентификацию пользователей можно выполнить одним из следующих способов:

  1. Google OAuth2 access tokens - Typically, the ability to read from and write to the Realtime Database is governed by Realtime Database Rules . But, you can access your data from a server and grant that server full read and write access to your data with a Google OAuth2 access token generated from a service account.

  2. Firebase ID tokens - You might also want to send requests authenticated as an individual user, like limiting access with Realtime Database Rules on the client SDKs. The REST API accepts the same Firebase ID tokens used by the client SDKs.

Токены доступа Google OAuth2

Any data that's publicly readable or writable according to your Realtime Database Rules is also readable and writable via the REST API without any authentication. However, if you want your server to bypass your Realtime Database Rules, you need to authenticate your read and write requests. Authentication through Google OAuth2 requires the following steps:

  1. Сгенерируйте токен доступа.
  2. Аутентифицируйтесь с помощью этого токена доступа.

Сгенерируйте токен доступа

REST API Realtime Database принимает стандартные токены доступа Google OAuth2 . Токены доступа можно сгенерировать, используя учетную запись службы с соответствующими правами доступа к вашей Realtime Database . Нажав кнопку «Сгенерировать новый закрытый ключ» в нижней части раздела « Учетные записи служб» консоли Firebase , вы можете легко сгенерировать новый файл ключа учетной записи службы, если у вас его еще нет.

Получив файл ключа учетной записи службы, вы можете использовать одну из клиентских библиотек Google API для генерации токена доступа Google OAuth2 со следующими необходимыми областями действия:

  • https://www.googleapis.com/auth/userinfo.email
  • https://www.googleapis.com/auth/firebase.database

Ниже приведены примеры реализаций, демонстрирующие создание токенов доступа Google OAuth2 для аутентификации в REST API Realtime Database на различных языках программирования:

Node.js

Использование клиентской библиотеки Google API для Node.js :

var {google} = require("googleapis");

// Load the service account key JSON file.
var serviceAccount = require("path/to/serviceAccountKey.json");

// Define the required scopes.
var scopes = [
  "https://www.googleapis.com/auth/userinfo.email",
  "https://www.googleapis.com/auth/firebase.database"
];

// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
  serviceAccount.client_email,
  null,
  serviceAccount.private_key,
  scopes
);

// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
  if (error) {
    console.log("Error making request to generate access token:", error);
  } else if (tokens.access_token === null) {
    console.log("Provided service account does not have permission to generate access tokens");
  } else {
    var accessToken = tokens.access_token;

    // See the "Using the access token" section below for information
    // on how to use the access token to send authenticated requests to
    // the Realtime Database REST API.
  }
});

Java

Использование клиентской библиотеки Google API для Java :

// Load the service account key JSON file
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

// Authenticate a Google credential with the service account
GoogleCredential googleCred = GoogleCredential.fromStream(serviceAccount);

// Add the required scopes to the Google credential
GoogleCredential scoped = googleCred.createScoped(
    Arrays.asList(
      "https://www.googleapis.com/auth/firebase.database",
      "https://www.googleapis.com/auth/userinfo.email"
    )
);

// Use the Google credential to generate an access token
scoped.refreshToken();
String token = scoped.getAccessToken();

// See the "Using the access token" section below for information
// on how to use the access token to send authenticated requests to the
// Realtime Database REST API.

Python

Используя библиотеку google-auth :

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

# Define the required scopes
scopes = [
  "https://www.googleapis.com/auth/userinfo.email",
  "https://www.googleapis.com/auth/firebase.database"
]

# Authenticate a credential with the service account
credentials = service_account.Credentials.from_service_account_file(
    "path/to/serviceAccountKey.json", scopes=scopes)

# Use the credentials object to authenticate a Requests session.
authed_session = AuthorizedSession(credentials)
response = authed_session.get(
    "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json")

# Or, use the token directly, as described in the "Authenticate with an
# access token" section below. (not recommended)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
access_token = credentials.token

Аутентификация с помощью токена доступа.

To send authenticated requests to the Realtime Database REST API, pass the Google OAuth2 access token generated above as the Authorization: Bearer <ACCESS_TOKEN> header or the access_token=<ACCESS_TOKEN> query string parameter. Here is an example curl request to read Ada's name:

curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?access_token=<ACCESS_TOKEN>"

Обязательно замените <DATABASE_NAME> на имя вашей Realtime Database , а <ACCESS_TOKEN> — на токен доступа Google OAuth2.

Успешный запрос будет обозначен HTTP-статусом 200 OK . Ответ будет содержать запрашиваемые данные:

{"first":"Ada","last":"Lovelace"}

Идентификационные токены Firebase

When a user or device signs in using Firebase Authentication , Firebase creates a corresponding ID token that uniquely identifies them and grants them access to several resources, such as Realtime Database and Cloud Storage . You can re-use that ID token to authenticate the Realtime Database REST API and make requests on behalf of that user.

Сгенерируйте идентификационный токен.

Чтобы получить токен Firebase ID на клиенте, выполните действия, описанные в разделе «Получение токенов ID на клиентах» .

Обратите внимание, что идентификационные токены истекают через короткий промежуток времени, и их следует использовать как можно быстрее после получения.

Аутентификация с помощью идентификационного токена.

To send authenticated requests to the Realtime Database REST API, pass the ID token generated above as the auth=<ID_TOKEN> query string parameter. Here is an example curl request to read Ada's name:

curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>"

Обязательно замените <DATABASE_NAME> на имя вашей Realtime Database , а <ID_TOKEN> — на токен идентификатора Firebase.

Успешный запрос будет обозначен HTTP-статусом 200 OK . Ответ будет содержать запрашиваемые данные:

{"first":"Ada","last":"Lovelace"}

Наследственные токены

Если вы все еще используете устаревшие токены аутентификации Firebase, мы рекомендуем обновить вашу REST-аутентификацию, выбрав один из описанных выше методов аутентификации.

The Realtime Database REST API still supports authentication via legacy authentication tokens, including secrets . Your Realtime Database secrets can be found in the Service Accounts section of the Firebase console.

Секреты — это учетные данные с длительным сроком действия. Мы рекомендуем генерировать новый секрет и отзывать существующий при удалении пользователей с доступом к секретам (например, владельцев) из проекта.