首页 > 解决方案 > 使用保护数据规则时,Firebase swift Permission Denied

问题描述

我正在尝试从 firebase 数据库中检索数据,但为了保护数据,我应该为 API 提供用户 ID,并且它应该用用户名来回答。

这是我的数据库格式:

users : {
"x0001": "John"
"x0002": "Samuel" 
"x0003": "Rachel"
}

以下是关于文档https://firebase.google.com/docs/database/security/securing-data的限制

  {
  "rules": {
    "users": {
        ".read": "query.equalTo != null",
        ".write": false
      }
  }
}

这是访问我的数据库的方法

func isUserExists(userId: String) {     
     Database.database().reference().child("users")
                .queryOrderedByKey()
                .queryEqual(toValue: userId)
            .observeSingleEvent(of: .value, with: { (snapshot) in
                print(snapshot.value as? String)

            }){ (error) in
                print("error: \(error.localizedDescription)")
           }
}

例如,当我使用 userId 调用此方法时

isUserExists(userId: "x0001") 

输出

error : Permission Denied

当我在没有约束的情况下进行测试时,它运行良好,所以我猜请求写得很好,但它不尊重这个约束

".read": "query.equalTo != null"

谢谢

标签: iosswiftfirebase-realtime-database

解决方案


推荐阅读