[英]How to read data from Firebase Realtime Database with the auth rule on web?
我在 Firebase 主機上有一個 web 應用程序,我需要從我的數據庫中讀取一些數據。 我可以通過".read"
權限讀取任何我想要的數據。
例如:
{
"users": {
".write": "true",
".read": "true"
},
...
}
上述規則工作正常,但當我設置auth
規則時,它不起作用。 這是我的auth
新規則:
{
"users": {
".read": "(auth != null && auth.uid == $userId)",
".write": "(auth != null && auth.uid == $userId)"
},
...
}
我得到的錯誤:客戶端沒有訪問所需數據的權限。
我正在嘗試在用戶登錄后訪問數據,並且我正在使用 Firebase 的預建用戶界面。
firebase.auth().onAuthStateChanged(async (firebaseUser) => {
if (firebaseUser) {
/* read the data */
}
}
我還可以讀取用戶的 JTW 令牌,並且我的數據庫路徑是正確的,但仍然無法正常工作。
我發現了這個問題: permission_denied at /: Client doesn't have permission to access the desired data
我在用戶登錄后啟動了應用程序,但它也沒有工作。 那么,為什么auth
規則不起作用。
注意:此規則適用於我的兩個移動應用程序(iOS 和 Android)
我的確切規則:
{
"rules": {
"users": {
"$userId": {
"single":{
"private": {
".read": "(auth != null && auth.uid == $userId)"
}
}
}
}
}
}
您的路徑中沒有定義 $userId。 假設您的用戶節點包含更多子節點,每個用戶一個,那么您的規則應如下所示:
{
"users": {
"$userId" {
// grants write access to the owner of this user account
// whose uid must exactly match the key ($userId)
".read": "(auth != null && auth.uid == $userId)",
".write": "(auth != null && auth.uid == $userId)"
}
},
...
}
現在這里userId
的值與該子節點的鍵相同,應該是用戶的 UID。
聊了很久更新:初始化第二個數據庫,如下圖:
const firebaseConfig = {...}
const app1 = firebase.initializeApp(firebaseConfig);
var database2 = app1.database("https://second-db-url.firebaseio.com/");
完成此配置后,然后提出您的請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.