【问题标题】:Firebase: do I need to send the uid everytime I post something in this case?Firebase:在这种情况下,我每次发布内容时都需要发送 uid 吗?
【发布时间】:2021-01-28 22:46:09
【问题描述】:

我试图限制只允许用户读取他发布到 firebase 的数据。 身份验证已到位。发布、读取和删除数据只是工作

但尚未为 firebase 数据库设置任何真正的规则。

我试图改变这个:

 {
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid"
      }
    }
  }
} 

这给了我一个 401 错误(未经授权)。现在我不确定问题可能是什么。我是否可能需要将 uid 显式添加到数据发送中? 所以firebase可以尝试匹配来自post和auth.uid的uid。

但我觉得这不足以保护数据。

编辑: 我正在使用的一些代码:

data.service.ts

  storeNotes() {
    const notes = this.noteService.getNotes();
    this.http
      .put(
        'https://XXXXXXX.firebaseio.com/notes.json',
        notes
      )
      .subscribe(response => {
        console.log(response);
      });
  }

note.service.ts

private notes: Note[] = [];

getNotes() {
    return this.notes.slice();
  }

note.model.ts

export class Note {
  public userName: string;
  public name: string;
  public description: string;


  constructor(userName: string, name: string, desc: string) {
    this.userName = userName;
    this.name = name;
    this.description = desc;
  }
}

我现在还没有发布身份验证数据,因为我不认为它们应该在这里相关。还是我错了?

【问题讨论】:

  • 您标记为 google-cloud-firestore,但您显示的安全性适用于 Firebase 实时数据库。虽然这两个数据库都是 Firebase 的一部分,但它们是完全独立的,一个的安全规则不适用于另一个。如果您使用的是 Cloud Firestore,请务必为该数据库设置正确的规则。
  • 您还应该显示查询受这些规则影响的数据库的应用代码。
  • @FrankvanPuffelen 好的,我在那里看到了我的错误。谢谢!
  • @DougStevenson 就是这么做的。

标签: typescript firebase firebase-realtime-database firebase-security


【解决方案1】:

您的安全规则只允许访问“users/{uid}”下的数据,但您的查询在“notes”下写入子项。您没有任何规则允许访问它。

要么您必须添加规则以允许访问“笔记”,要么您访问了数据库中的错误位置。如果您想将每个用户的数据存储在“users/{uid}”下,那么您应该将其构建到您的 URL 路径中,如 documentation 所示,例如 /users/{uid}/notes

【讨论】:

  • 谢谢。是的,现在看起来几乎很明显......在该代码上看起来不够接近。在我的情况下,您将如何解决这个问题?我只是将 users/{uid} 更改为 notes/{uid} 但没有帮助。
  • 我不知道。你必须自己决定你想要完成什么。您可以根据自己的应用需求来构建数据库。
  • 我查看了文档,但仍然不确定。我所做的是用“笔记”替换“用户”。这应该是正确的。但不知何故不是。我不明白为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多