![](/img/trans.png)
[英]How can we allow a particular User UID to have only access to a particular collection in Firestore security rules?
[英]Can not write firestore security rule for top level collection (list permission) given a specific authenticated user (uid) for an android app
我剛剛開始使用 Firebase 服務(firestore),我不知道為什么以下不起作用。
這是我的安全規則文件:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents/{document=**} {
allow read, write: if request.auth.uid == resource.data.user_id;
}
}
我的數據庫結構如下:
稱為備忘錄的頂級集合包含文檔。 在我的示例中,我只有一個“H5i5p0zenBwkV7vsS12G”。 它以其自動生成的 ID 命名。 該文檔有 2 個數據字段。 一個“user_id”字符串數據等於“7llpal4k0xVxILawceAPPsJe3Vy1”,一個“title”字符串數據等於“Hello Firestore User”。
/memos/H5i5p0zenBwkV7vsS12G with some data: {
title: "Hello Firestore User"
user_id: "7llpal4k0xVxILawceAPPsJe3Vy1"
}
當我使用測試工具和我的 android 應用程序運行get (/databases/(default)/documents/memos/H5i5p0zenBwkV7vsS12G) 操作時,它工作得很好。
但每次我要求使用備忘錄收藏列表
Firebase.firestore.collection("memos")
它因權限被拒絕異常而失敗。 這是相關的日志:
2021-11-08 19:36:00.946 2996-3045/com.ygoular.memo I/Firestore: (23.0.4) [WatchStream]: (e04cf9f) Stream sending: # com.google.firestore.v1.ListenRequest@7a872c89
add_target {
query {
parent: "projects/memo-da978/databases/(default)/documents"
structured_query {
from {
collection_id: "memos"
}
order_by {
direction: ASCENDING
direction_value: 1
field {
field_path: "__name__"
}
}
}
}
target_id: 2
}
database: "projects/memo-da978/databases/(default)"
2021-11-08 19:36:00.946 2996-3045/com.ygoular.memo I/Firestore: (23.0.4) [FirestoreCallCredentials]: Successfully fetched token.
2021-11-08 19:53:05.815 4440-4480/com.ygoular.memo I/Firestore: (23.0.4) [WatchStream]: (2faa0c0) Stream received: # com.google.firestore.v1.ListenResponse@c4bcaabe
target_change {
cause {
code: 7
message: "Missing or insufficient permissions."
}
target_change_type: REMOVE
target_change_type_value: 2
target_ids: 2
}
此調用是在經過身份驗證后進行的。 我確信我的應用程序在那一刻已經過身份驗證,因為如果我使用以下內容修改安全規則:
allow read, write: if request.auth.uid != null
它通過並返回可用的備忘錄。 我也確定用戶 ID 應該匹配,因為我粘貼了返回的值
FirebaseAuth.getInstance().currentUser.uid
執行電話身份驗證后,到數據庫中的備忘錄“user_id”字段。 對於該提供商(電話),此 ID 永遠不會更改。
這是從 logcat 中獲得的 uid:
2021-11-08 19:53:05.633 4440-4440/com.ygoular.memo E/Test: uid: 7llpal4k0xVxILawceAPPsJe3Vy1
我可以完成這項工作的唯一方法是創建一個頂級集合 /users ,其文檔名稱作為其用戶 ID。 在這種情況下,文檔包含子集合 /memos 並且規則看起來像這樣:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents/users/{userId}/{anythingBehind=**} {
allow read, write: if request.auth.uid == userId;
}
}
如果您知道如何解決此問題,請告訴我! :) 非常感謝。
規則不是過濾器
我再說一遍
規則不是過濾器
事實上,我會讓文檔再次重復一遍:
https://firebase.google.com/docs/firestore/security/rules-query
規則不檢查每個記錄以查看每個記錄是否被允許。 規則檢查以查看查詢 AS WRITTEN是否可能與不允許的記錄匹配 - 在這種情況下,不允許使用 ENTIRE QUERY。 它甚至不檢查其中一條記錄是否可以工作 - 您必須執行至少指定 user_Id 字段的查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.