简体   繁体   中英

How to match a user's uid stored in document field inside Firebase security rule for Firestore

I want to check for the UID stored in the document field of a document (of the parent collection named premiumID ) against the UID of the user requesting the data. In simpler words, I want the user to only access the document which contains his UID.

Here's what I have done until now

service cloud.firestore {
  match /databases/{database}/documents {

    match /premiumID/{docId} {

      function userData() {
        return resource.data.uid
      }

      allow update: if userData() == request.auth.uid;
      allow delete: if userData() == request.auth.uid;
      allow create: if request.auth.uid != null;
      allow read: if userData() == request.auth.uid;
    }    
  }
}

Here's what my DB looks like-

在此处输入图片说明

Here's how I am testing it. This gives me read and write denied .

在此处输入图片说明

The rule allow write: if request.auth.uid == request.resource.data.uid; checks if user authentication is the same as the field uid that the document contains. But as said in the comments of your question your collection name doesn't match the rule that you are using.

Check this site it contains very useful information about firebase rules. It really helped me when I started using firebase rules for more complicated rules.

I think if you want to match a document you have to use {document} instead of {docId} . I also had similar problem and changing to {document} solved it.

match /pID/{document}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM