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 控制台「服務帳戶」部分底部的「產生新的私密金鑰」按鈕,即可輕鬆產生新的服務帳戶金鑰檔案。
取得服務帳戶金鑰檔案後,您可以使用 Google API 用戶端程式庫,產生 Google OAuth2 存取權杖,並使用下列必要範圍:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/firebase.database
以下是一些實作範例,說明如何建立 Google OAuth2 存取權杖,以各種語言向 Realtime Database 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
使用 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 密鑰。
密鑰是長期憑證,從專案中移除具有私密存取權的使用者 (例如擁有者) 時,建議您產生新的私密金鑰並撤銷現有金鑰。