Firebase SDK 代表您處理與 Firebase 實時數據庫的所有身份驗證和通信。但是,當您處於沒有客戶端 SDK 的環境中或者您想要避免持久數據庫連接的開銷時,您可以使用實時數據庫 REST API 來讀取和寫入數據。
通過以下方法之一對用戶進行身份驗證:
Google OAuth2 訪問令牌- 通常,讀取和寫入實時數據庫的能力受實時數據庫規則控制。但是,您可以從服務器訪問您的數據,並使用從服務帳戶生成的 Google OAuth2 訪問令牌授予該服務器對您的數據的完全讀寫訪問權限。
Firebase ID 令牌- 您可能還希望發送以個人用戶身份進行身份驗證的請求,例如使用客戶端 SDK 上的實時數據庫規則限制訪問。 REST API 接受客戶端 SDK 使用的相同 Firebase ID 令牌。
谷歌 OAuth2 訪問令牌
根據實時數據庫規則公開可讀或可寫的任何數據也可通過 REST API 進行讀寫,無需任何身份驗證。但是,如果您希望服務器繞過實時數據庫規則,則需要對讀取和寫入請求進行身份驗證。通過 Google OAuth2 進行身份驗證需要以下步驟:
- 生成訪問令牌。
- 使用該訪問令牌進行身份驗證。
生成訪問令牌
實時數據庫 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
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.
}
});
爪哇
// 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 控制台的服務帳戶部分找到。