Firestore权限异常:匹配用户ID与文档ID时提示权限不足
It looks like you're trying to lock down Firestore access so users can only read/write their own data (their users document and nested Tasks subcollection), but your rule setup is missing the specific path matching needed to make that work. Let's break down the correct approach.
The Problem with Your Original Rule (and Why the Restricted Version Fails)
Your initial open rule (match /{document=**} { allow read, write: if request.auth.uid != null; }) works because it allows any authenticated user access to everything. But when you try to restrict to user-owned data, you probably didn't structure the path matches correctly to target the users collection and its nested Tasks subcollection explicitly.
Correct Security Rules for User-Owned Data
Here's the rule set that will enforce the permission model you want:
service cloud.firestore { match /databases/{database}/documents { // Control access to the user's main document in the users collection match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; // Control access to the Tasks subcollection under the user's document match /Tasks/{taskId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } } }
How This Works
- Top-level
users/{userId}match: This captures the ID of the document in theuserscollection into theuserIdvariable. The rule checks that the authenticated user's UID matches thisuserId—so only the owner can read or write their own user document. - Nested
Tasks/{taskId}match: This targets every document in theTaskssubcollection under a user's document. It reuses theuserIdvariable from the parent match, ensuring the user can only interact with tasks that belong to their own user document.
Common Pitfalls to Avoid
Document ID Mismatch: Make sure you're creating the user's document with their UID as the document ID. For example, when saving user data after Google login:
// Correct: Use user.uid as the document ID firebase.firestore().collection('users').doc(user.uid).set({ // User data here });If you use Firestore's auto-generated IDs instead, the
userIdin the rule won't matchrequest.auth.uid, leading to permission errors.Forgetting Subcollections: If you only set rules for the
userscollection and not the nestedTaskssubcollection, any request to access tasks will fail—Firestore doesn't inherit permissions from parent collections automatically.Overlapping Wildcard Rules: If you leave the original
/{document=**}wildcard rule in place, it might override your specific rules. Always remove broad wildcard rules when implementing granular permissions, since Firestore uses the most specific path match first.
内容的提问来源于stack exchange,提问作者lironT74

