如何在Firebase Firestore安全规则中获取{item}参数的值?
Accessing Path Parameters in Firestore Security Rules
Absolutely! You can access path parameters in Firebase Firestore security rules, and it’s a core part of writing granular, secure rules—similar to how you use context.params in Cloud Functions, just with a simpler syntax.
When you define a match pattern with a placeholder like {item} or {user}, that placeholder becomes a direct variable you can use within the rule’s conditions. Let’s break this down using your provided rule code as an example:
Example from Your Code
First, here’s your original rules formatted for readability:
service cloud.firestore { match /databases/{database}/documents { match /notifications/{user} { allow read, write: if request.auth.uid != null; } match /items/{item} { allow read: if true; allow write: if false; } } }
Using Path Parameters in Rules
- For the
match /notifications/{user}block: Theuservariable holds the value of the{user}segment in the document path (e.g., if the path is/notifications/abc123,userequals"abc123"). You could use this to tighten security, like restricting access only to the user whose ID matches the path:match /notifications/{user} { allow read, write: if request.auth.uid == user; } - For the
match /items/{item}block: Theitemvariable represents the document ID in theitemscollection. If you wanted to allow write access only when the authenticated user’s UID matches the item ID, you’d write:match /items/{item} { allow read: if true; allow write: if request.auth.uid == item; }
This works exactly like context.params.item in Cloud Functions—you’re just referencing the placeholder variable directly in your rule conditions.
内容的提问来源于stack exchange,提问作者Ayan Bora
相关产品推荐
相关产品推荐

