Firebase:连接到同一Firestore数据库的已验证客户端和来宾客户端



我的用例是,我有一个web应用程序,我听Firestore集合。其中一个集合是针对匿名认证足够的公共用户的。第二个集合是针对登录用户的,因此我在此之后实现了自定义令牌验证。https://firebase.google.com/docs/auth/web/custom-auth。一旦用户登录,我们启动一个Web Worker来初始化应用程序并收听Firestore。

我的问题是,当用户登录时,第二个订阅,经过身份验证的订阅,工作,但如果我试图从同一选项卡转到公共页面,我不需要验证令牌,我得到这个错误。

Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
at new Ur (prebuilt.js:184:9)
at prebuilt.js:10612:34
at br.<anonymous> (prebuilt.js:10564:21)
at Bt (eventtarget.js:351:23)
at qt (eventtarget.js:481:26)
at Ir.wa (webchannelbasetransport.js:369:17)
at Ke (webchannelbase.js:2258:25)
at Fe (channelrequest.js:951:12)
at Ne.N.Ia (channelrequest.js:743:10)
at Ne.N.gb (channelrequest.js:603:10)

两个订阅使用相同的firebase应用程序,相同的配置。

更多信息:

这些是规则

function isSignedIn(){
return request.auth != null;
}
function isDocumentOwner(docid) {
// checks if user id is the same as the document id
return isSignedIn() && request.auth.uid == docid;
}
//this collection can be accessed for guest/anonymous users
match /guests/{uid} {
allow read, write: if isDocumentOwner(uid);
}
//this collection in only accessible for logged in users(JWT token)
match /users/{uid} {
allow read, write: if isDocumentOwner(uid);
}

初始化代码

客人页面:

const app = initializeApp(firebaseConfig);
db = getFirestore(app);
auth = getAuth();
signInAnonymously(auth);
onAuthStateChanged(auth, (loginUser) => {
if (loginUser) {
user = loginUser;
} else {
unsubscribe();
}
});

登录页面:

const app = initializeApp(firebaseConfig);
db = getFirestore(app);
auth = getAuth();
signInWithCustomToken(auth, customToken);
onAuthStateChanged(auth, (loginUser) => {
if (loginUser) {
user = loginUser;
} else {
unsubscribe();
}
});

我明白了。我从两个地方连接到同一个firebase应用程序。第一个来自Web Worker,使用自定义令牌认证,第二个来自同一浏览器的不同选项卡,使用匿名登录。当第二个连接尝试使用匿名认证发起连接时,它不起作用,因为应用程序已经使用自定义令牌启动,这部分规则

失败了。
request.auth.uid == docid

request.auth。Uid为已登录用户的Uid。

修复:

我必须创建另一个应用程序和一组用于登录用户的配置。然后,当我初始化和授权应用程序时,我必须给出一个应用程序名称。

const app = initializeApp(firebaseConfig, 'new-app');
db = getFirestore(app);
auth = getAuth(app);
signInWithCustomToken(auth, customToken);
onAuthStateChanged(auth, (loginUser) => {
if (loginUser) {
user = loginUser;
} else {
unsubscribe();
}
});

最新更新