Firestore安全规则允许用户访问其数据

时间:2018-03-13 06:21:48

标签: firebase google-cloud-firestore firebase-security-rules

我想写一个这样的规则:

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

也就是说,如果该用户是经过身份验证的用户,我希望允许对所有用户数据进行所有读写操作。

不幸的是,这不起作用。我收到一条错误,指出我无权访问数据。

3 个答案:

答案 0 :(得分:4)

此代码解决了问题:

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

我认为这是因为您需要授予对/users/{userId}以及/users/{userId}/{anyDoc=**}的访问权限。

答案 1 :(得分:0)

来自official documentation

  

另一种常见模式是确保用户只能读写   自己的数据:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}
  

如果您的应用使用Firebase身份验证,则request.auth变量   包含客户端请求的身份验证信息   数据。

答案 2 :(得分:0)

请注意,如果您在数据库中创建了一个“用户”表,并使用应用程序已知的用户填充了该表(可能是从FireBase的用户部分“身份验证/用户”中复制的),则此起作用Web控制台)。

无法通过这种方式引用经过Firestore身份验证的用户表。我发现缺乏信息非常令人困惑,因为所有示例和Firestore文档都使您相信可以以这种方式访问​​通过Web控制台创建的用户,在尝试从用户表中读取时总是会导致出现``拒绝访问''消息。