c# - 如何使我的 Firebase 实时数据库规则正常工作?
问题描述
我的 Firebase 实时数据库有两个不同的规则。一种只允许经过身份验证的用户进行读写,而另一种则更复杂。它只允许经过身份验证的用户从“房间”节点读取和写入数据,并且它允许用户在“用户”节点中仅使用自己的数据。但是,当我使用第二条规则时,由于某些我不知道的原因,我收到以下错误。
System.NullReferenceException:对象引用未设置为对象的实例
我的两条规则是:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
},
"rooms": {
".read": "auth != null",
".write": "auth != null"
}
}
}
我的代码包含导致错误的行(第 3 行):
void HandleValueChanged(object sender, ValueChangedEventArgs args) {
if(auth.CurrentUser != null) {
currentRoom = args.Snapshot.Child(auth.CurrentUser.UserId).Child("currentRoom").Value.ToString(); //this line causes the error
FirebaseDatabase.DefaultInstance.GetReference("rooms").Child(currentRoom).Child("members").Child(auth.CurrentUser.UserId).Child("type").GetValueAsync().ContinueWith(task => {
if (task.IsFaulted) {
// Handle the error...
} else if (task.IsCompleted) {
DataSnapshot snapshot = task.Result;
charType = snapshot.Value.ToString();
}
});
}
}
我试图在 Firebase 的规则操场上做一些事情,但我没有设法在那里找到解决方案。HandleValueChanged 方法正在使用用户节点:
FirebaseDatabase.DefaultInstance.GetReference("users").ValueChanged += HandleValueChanged;
解决方案
您的代码尝试读取整个users
节点:
FirebaseDatabase.DefaultInstance.GetReference("users").ValueChange
但是您的安全规则只允许用户读取他们自己的节点:
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
},
由于用户无权访问所有/users
,因此拒绝从该节点读取。
问题是规则不是过滤器,因此它们不会自行过滤数据。相反,他们只是确保用户执行的操作不会与您为他们设置的规则冲突。而且由于您没有授予任何人对 (all of)/users
的读取权限,因此读取被拒绝。
在您的情况下,我强烈建议您简单地更改代码以仅访问用户确实有权访问的注释:
String uid = Firebase.Auth.FirebaseAuth.DefaultInstance.CurrentUser.UserId;
FirebaseDatabase.DefaultInstance.GetReference("users").Child(uid).ValueChanged = ...
在其他一些情况下,您可能能够结合查询和安全规则来满足您的需求。查询只请求用户有权访问的数据,安全规则确保查询与这些规则匹配。有关这方面的更多信息,请参阅有关基于查询的规则的文档。
推荐阅读
- django - django-modeltranslation:如何禁用显示没有翻译的语言的对象(例如帖子)?
- angular - 带有查询参数的角度路由不起作用
- r - 使用 ggcorrplot2 的 R 相关图:“x 轴”标签被裁剪
- c++ - 如何将参数添加到流缓冲区c ++
- validation - 如何保存具有验证规则的记录
- android - 不关注此内容时显示 TextInputEditText 的标签
- c# - WPF SkiaSharp Canvas 点击鼠标位置
- java - 在使用新的 spring-data-neo4j 6.0.0-SNAPSHOT 进行测试期间获取到内存中 neo4j 实例的连接错误
- javascript - 为处理事件的普通 Promise 命名为 Promise Chainy
- php - 为什么 PHP 分配的内存比加载的图像多?