Firestore rules not working for userId

2019-07-04 05:51发布

I'm having a simple collection users, document id is using the uid with name string enter image description here

I'm using angularfire2 to connect to the collection

this.users = afs.collection<User>('users').valueChanges();

I'm using firebase authentication. When displaying the user id, I get 4NxoeUeB4OXverhHhiw86eKl0Sj1 which match with the user document.

this.afAuth.authState.subscribe(auth => console.log(auth.uid));

I'm trying to add rules for the collection. If I use the rules below, I get error Missing or insufficient permissions.

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth.uid == userId;
    }
  }
}`

If I change the rule to request.auth != null the data is shown.

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth != null;
    }
  }
}`

What could I have done wrong? I'm also trying a few different rules eg. resource.data.name != null. It is also not working.

I am testing the rule. The end result I want a readers array field and writers array field so I can try something like request.auth.uid in resource.data.readers to control access to the document

1条回答
放我归山
2楼-- · 2019-07-04 06:31

You are trying to get /users/* but you only have access to /users/{yourid}.

You should only retrieve data you have access to, so you need to filter your query even if you actually only have one document.

// either by adding a field in your doc
afs.collection('users', ref => ref.where('id', '==', auth.uid))

// or by getting the document directly
afs.collection('users').doc(auth.uid)

When performing a rules check on a query, Cloud Firestore Security Rules will check to ensure that the user has access to all results before executing the query. If a query could return results a user doesn't have access to, the entire query fails and Firestore returns an error.

Source : https://cloud.google.com/firestore/docs/security/secure-data#shallow_queries

查看更多
登录 后发表回答