【发布时间】:2022-10-24 14:55:17
【问题描述】:
我想在服务器端渲染期间从 Firestore 获取数据。我知道我可以使用REST API(并将令牌附加到请求的标头),但我不想在服务器端编写 REST 请求,然后使用standard Firestore queries 在客户端复制相同的请求。在客户端上,由于实时更新,我更喜欢标准查询(无 REST)。而且我想在服务器上重用来自客户端的查询(即使没有实时更新的好处)。
我在服务器上手动验证令牌:
import admin from 'firebase-admin';
import { initializeApp, getApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const firebaseApp = initializeApp(config);
const db = getFirestore(firebaseApp);
const decodedIdToken = await admin.auth().verifySessionCookie(sessionCookie);
// => token verified: decodedIdToken.userId = "xxx"
但是当我想执行查询时:
import { collection, getDocs } from 'firebase/firestore';
const querySnapshot = await getDocs(collection(db, 'myCollection'));
我得到错误:
{
"code": "permission-denied",
"name": "FirebaseError"
}
Firestore 规则:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
在客户端,可以使用onAuthStateChanged 解决错误,但我不能在服务器上使用此侦听器。
有没有办法使用手动验证的令牌运行 Firestore 查询?
【问题讨论】:
-
您能否根据此documentation 为您的项目提供 Firestore 规则?
-
@RobertG 问题已根据规则更新。
标签: firebase google-cloud-firestore firebase-authentication server-side-rendering