[英]Firebase Security Rules to specific Collection?
我有三個 collections, Collect 1
和Collection 2
,只能由經過身份驗證的用戶讀取。 第三個集合是Users
,只有經過身份驗證的用戶才能讀取、寫入、更新和刪除,但只能讀取具有各自 UID 的文檔。 當前規則適用於所有集合。 當前的安全規則是:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if request.auth != null;
}
}
}
我只想在這里添加一些細節或示例。 在此規則中,用戶的 UID 存儲為文檔 ID。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
allow read, write, delete: if request.auth != null && request.auth.uid == uid;
}
match /collection1/{document} {
allow read: if request.auth != null;
}
match /collection2/{document} {
allow read: if request.auth != null;
}
}
}
我在本地模擬器中做了一些測試代碼:
firebase.firestore().doc('/users/'+user.uid).get().then(() => {
console.log("user self path granted")
}).catch(() => console.log("user other path deny"));
firebase.firestore().doc('/users/other').get().then(() => {
console.log("user other path granted")
}).catch(() => console.log("user other path deny"));
firebase.firestore().doc('/collection1/tCa4m3nGNjX4s3i1Uvc7').get().then(() => {
console.log("collection1 path granted")
}).catch(() => console.log("collection1 path deny"));
firebase.firestore().doc('/collection2/tCa4m3nGNjX4s3i1Uvc7').get().then(() => {
console.log("collection2 path granted")
}).catch(() => console.log("collection2 path deny"));
firebase.firestore().doc('/collection3/OvGk404uSdMFQAwN1qoA').get().then(() => {
console.log("collection3 path granted")
}).catch(() => console.log("collection3 path deny"));
Output
user self path granted
user other path deny
collection1 path granted
collection2 path granted
collection3 path deny
只有經過身份驗證的用戶才能讀取、寫入、更新和刪除,但只有具有各自 UID 的文檔
您沒有說明用戶的 UID 如何與 Firestore 文檔 ID 相關聯。 基本上有兩種情況:
1/ 用戶的UID為Firestore文檔ID
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{docId} {
allow read, write: if request.auth != null && request.auth.uid == docId;
}
}
}
2/ 用戶的 UID 存儲在文檔 ID 的一個字段中(例如: userId
字段)
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{docId} {
allow read: if request.auth != null && resource.data.userId == userId;
allow write: if request.auth != null && request.resource.data.userId == userId;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.