驗證 REST 請求

Firebase SDK 代表您處理與 Firebase 即時資料庫的所有身份驗證和通訊。但是,當您處於沒有客戶端 SDK 的環境中或您想要避免持久資料庫連線的開銷時,您可以使用即時資料庫 REST API 來讀取和寫入資料。

透過以下方法之一對使用者進行身份驗證:

  1. Google OAuth2 存取令牌- 通常,讀取和寫入即時資料庫的能力受即時資料庫規則控制。但是,您可以從伺服器存取您的數據,並使用從服務帳戶產生的 Google OAuth2 存取權令牌授予該伺服器對您的資料的完全讀寫存取權。

  2. Firebase ID 令牌- 您可能還想傳送以個人使用者身分進行驗證的請求,例如使用用戶端 SDK 上的即時資料庫規則限制存取。 REST API 接受客戶端 SDK 使用的相同 Firebase ID 令牌。

Google OAuth2 存取權令牌

根據即時資料庫規則公開可讀或可寫入的任何資料也可透過 REST API 進行讀寫,無需任何身份驗證。但是,如果您希望伺服器繞過即時資料庫規則,則需要對讀取和寫入請求進行身份驗證。透過 Google OAuth2 進行身份驗證需要以下步驟:

  1. 產生訪問令牌。
  2. 使用該存取令牌進行身份驗證。

產生訪問令牌

即時資料庫 REST API 接受標準Google OAuth2 存取權令牌。可以使用對即時資料庫具有適當權限的服務帳戶產生存取權杖。點擊 Firebase 控制台「服務帳戶」部分底部的「產生新私鑰」按鈕,您可以輕鬆產生新的服務帳戶金鑰檔案(如果您還沒有)。

擁有服務帳戶金鑰檔案後,您可以使用Google API 用戶端程式庫之一產生具有以下所需範圍的 Google OAuth2 存取權令牌:

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

以下是一些範例實現,展示如何建立 Google OAuth2 存取權杖以對各種語言的即時資料庫 REST API 進行身份驗證:

Node.js

使用Node.js 的 Google API 客戶端程式庫

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 用戶端程式庫

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

使用訪問令牌進行身份驗證

若要將經過驗證的請求傳送至即時資料庫 REST API,請將上述產生的 Google OAuth2 存取權杖作為Authorization: Bearer <ACCESS_TOKEN>標頭或access_token=<ACCESS_TOKEN>查詢字串參數傳遞。下面是一個讀取 Ada 名字的curl請求範例:

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

確保將<DATABASE_NAME>替換為即時資料庫的名稱,將<ACCESS_TOKEN>替換為 Google OAuth2 存取權令牌。

成功的請求將由200 OK HTTP 狀態碼指示。回應包含正在檢索的資料:

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

Firebase ID 令牌

當使用者或裝置使用 Firebase 驗證登入時,Firebase 會建立一個對應的 ID 令牌來唯一標識他們並授予他們對多種資源(例如即時資料庫和雲端儲存)的存取權。您可以重複使用該 ID 令牌來驗證即時資料庫 REST API 並代表該使用者發出請求。

產生 ID 令牌

若要從用戶端擷取 Firebase ID 令牌,請依照在用戶端上擷取 ID 令牌中的步驟操作。

請注意,ID 令牌會在短時間內過期,取回後應盡快使用。

使用 ID 令牌進行身份驗證

若要將經過驗證的請求傳送至即時資料庫 REST API,請將上面產生的 ID 令牌作為auth=<ID_TOKEN>查詢字串參數傳遞。下面是一個讀取 Ada 名字的curl請求範例:

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

確保將<DATABASE_NAME>替換為即時資料庫的名稱,將<ID_TOKEN>替換為 Firebase ID 令牌。

成功的請求將由200 OK HTTP 狀態碼指示。回應包含正在檢索的資料:

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

遺留代幣

如果您仍在使用舊版 Firebase 驗證令牌,我們建議您將 REST 驗證更新為上述驗證方法之一。

即時資料庫 REST API 仍然支援透過舊版身份驗證令牌(包括金鑰)進行身份驗證。您的即時資料庫機密可以在 Firebase 控制台的服務帳戶部分找到。

秘密是長期有效的憑證。當從專案中刪除具有秘密存取權限的使用者(例如所有者)時,我們建議產生一個新的秘密並撤銷現有的秘密。