Firebase SDK 會代表您處理與 Firebase Realtime Database 的所有驗證和通訊作業。不過,如果環境沒有用戶端 SDK,或您想避免持續連線至資料庫的負擔,可以使用 Realtime Database REST API 讀取及寫入資料。
透過下列任一方法驗證使用者:
Google OAuth2 存取權杖:一般來說,Realtime Database 的讀取和寫入權限是由 Realtime Database 規則控管。不過,您可以透過伺服器存取資料,並使用服務帳戶產生的 Google OAuth2 存取權杖,授予該伺服器完整的資料讀寫權限。
Firebase ID 權杖:您可能也想以個別使用者身分傳送經過驗證的要求,例如使用用戶端 SDK 上的 Realtime Database 規則限制存取權。REST API 接受與用戶端 SDK 相同的 Firebase ID 權杖。
Google OAuth2 存取權杖
根據 Realtime Database 規則,任何可公開讀取或寫入的資料,也可以透過 REST API 讀取和寫入,不需經過任何驗證。不過,如果您希望伺服器略過 Realtime Database 規則,則需要驗證讀取和寫入要求。透過 Google OAuth2 驗證需要執行下列步驟:
- 產生存取權杖。
- 使用該存取權杖進行驗證。
產生存取權杖
Realtime Database REST API 接受標準 Google OAuth2 存取權杖。您可以使用具備 Realtime Database 適當權限的服務帳戶,產生存取權杖。如果您還沒有服務帳戶金鑰檔案,只要按一下 Firebase 控制台「Service Accounts」(服務帳戶) 區段底部的「Generate New Private Key」(產生新的私密金鑰) 按鈕,即可輕鬆產生新的服務帳戶金鑰檔案。
取得服務帳戶金鑰檔案後,您可以使用其中一個 Google API 用戶端程式庫,產生具有下列必要範圍的 Google OAuth2 存取權杖:
https://www.googleapis.com/auth/userinfo.emailhttps://www.googleapis.com/auth/firebase.database
以下是幾個實作範例,說明如何建立 Google OAuth2 存取權杖,以各種語言向 Realtime Database REST API 進行驗證:
Node.js
使用 Google API Client Library for 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
使用適用於 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
使用存取權杖進行驗證
如要將經過驗證的要求傳送至 Realtime Database 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> 替換為 Realtime Database 的名稱,並將 <ACCESS_TOKEN> 替換為 Google OAuth2 存取權杖。
如果要求成功,系統會傳回 200 OK HTTP 狀態碼。回應包含要擷取的資料:
{"first":"Ada","last":"Lovelace"}
Firebase ID 權杖
當使用者或裝置使用 Firebase Authentication 登入時,Firebase 會建立對應的 ID 權杖,用來識別使用者或裝置,並授予 Realtime Database 和 Cloud Storage 等多項資源的存取權。您可以重複使用該 ID 權杖來驗證 Realtime Database REST API,並代表該使用者提出要求。
產生 ID 權杖
如要從用戶端擷取 Firebase ID 權杖,請按照「在用戶端擷取 ID 權杖」中的步驟操作。
請注意,ID 權杖會在短時間內失效,因此取得後應盡快使用。
使用 ID 權杖進行驗證
如要將已驗證的要求傳送至 Realtime Database REST API,請將上方產生的 ID 權杖做為 auth=<ID_TOKEN> 查詢字串參數傳遞。以下是讀取 Ada 姓名的 curl 要求範例:
curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>"
請務必將 <DATABASE_NAME> 替換為 Realtime Database 的名稱,並將 <ID_TOKEN> 替換為 Firebase ID 權杖。
如果要求成功,系統會傳回 200 OK HTTP 狀態碼。回應包含要擷取的資料:
{"first":"Ada","last":"Lovelace"}
舊版權杖
如果您仍在使用舊版 Firebase 驗證權杖,建議將 REST 驗證更新為上述其中一種驗證方式。
Realtime Database REST API 仍支援透過舊版驗證權杖 (包括密鑰) 進行驗證。您可以在 Firebase 控制台的「Service Accounts」(服務帳戶) 專區找到 Realtime Database 密鑰。
密鑰是長期憑證。從專案中移除具有密鑰存取權的使用者 (例如擁有者) 時,建議您產生新的密鑰,並撤銷現有的密鑰。