Firestore规则中Firebase Installation授权令牌的验证方法及特定安装专属集合访问实现问询
Great question! Let's break this down step by step since Firestore security rules don't have built-in support for Firebase Installation tokens, but there's a way to make this work with a bit of extra setup.
Short answer: Not directly, but you can implement this by combining Firestore security rules with a Cloud Function to validate the token and retrieve the associated Installation ID.
Firestore's rule language doesn't include native methods to parse or verify Firebase Installation Service (FIS) tokens. However, you can pass the token from your client to Firestore via request headers, then call a Cloud Function from your rules to validate the token and check if it matches the Installation ID in your collection path.
Here's a step-by-step implementation:
1. Retrieve the Token on the Client
First, use the Firebase Installations SDK to get the FIS token and associated Installation ID in your client app. Example code for web:
import { getInstallations } from "firebase/installations"; import { getFirestore, doc, setDoc } from "firebase/firestore"; const installations = getInstallations(firebaseApp); const { token, installationId } = await installations.getToken(); // When making a Firestore request, include the token in custom headers const db = getFirestore(firebaseApp); const docRef = doc(db, "MyPrivateInstallationCollection", installationId); await setDoc(docRef, { someData: "hello world" }, { headers: { "X-Firebase-Installation-Token": token } });
2. Create a Cloud Function to Validate the Token
Write a Callable Cloud Function that uses the Firebase Admin SDK to verify the FIS token and return the corresponding Installation ID:
const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); exports.validateInstallationToken = functions.https.onCall(async (data, context) => { const { token } = data; if (!token) { throw new functions.https.HttpsError("invalid-argument", "Token is required"); } try { // Verify the token using the Admin SDK const installation = await admin.installations().verifyToken(token); return { installationId: installation.installationId }; } catch (err) { throw new functions.https.HttpsError("unauthenticated", "Invalid or expired token"); } });
3. Update Firestore Security Rules
Modify your rules to check for the presence of the token header, call the validation function, and ensure the returned Installation ID matches the path parameter:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /MyPrivateInstallationCollection/{installationId} { allow read, write: if // Ensure the token header exists request.headers['X-Firebase-Installation-Token'] != null && // Validate the token and match the Installation ID functions.invoke('validateInstallationToken', { token: request.headers['X-Firebase-Installation-Token'] }).installationId == installationId; } } }
- Token Lifecycle: FIS tokens are short-lived (usually 1 hour) and the SDK automatically refreshes them. Make sure your client handles token refresh seamlessly to avoid authentication failures.
- Security: Never expose the token to untrusted parties. Only send it directly from your client to Firestore/Cloud Functions over HTTPS.
- Performance: Each Firestore request will trigger a Cloud Function call, which adds some latency and cost. If you have high-traffic scenarios, consider caching valid token-Installation ID pairs temporarily (but ensure you respect token expiration).
- Fallback Options: If strict Installation-level access isn't critical, you could alternatively link Installation IDs to Firebase Auth users (even anonymous ones) and use Auth-based rules. But this doesn't use FIS tokens directly.
内容的提问来源于stack exchange,提问作者narduk

