限制对 Firebase-Database 的访问,auth.uid 不起作用

Kar*_*ann 5 google-authentication firebase firebase-authentication firebase-realtime-database

我想限制对 Firebase 数据库的访问,以便只有我授权的用户才能对其进行写入。但几乎所有地方提出的解决方案似乎都不适合我。

我的控制台中总是出现 401(未经授权)错误。

我尝试了两种方法来检查正确的用户是否登录,但没有一种对我有用:

1. uid硬编码在规则中:

{
"rules": {
  ".read": true,
  ".write": "auth.uid === 'UID'")",
    }
}
Run Code Online (Sandbox Code Playgroud)

2. 数据库中的uid

{
"rules": {
  ".read": true,
  ".write": "root.child('users').hasChild(auth.uid)",
    }
}
Run Code Online (Sandbox Code Playgroud)

在这两种方式中,我都使用了 Firebase-Authentication 概述中提供的 uid。我使用 Google 作为登录提供商。

ʍѳђ*_*ઽ૯ท 4

文档中:

以下是向经过身份验证的用户授予写入访问权限的规则示例/users/<uid>/,其中<uid> 是通过 Firebase 身份验证获取的用户 ID。


编辑:

对于通过 Firebase 身份验证的特定路径和当前获取的用户,这应该有所帮助:

{
  "rules": {
    "YourSpecificPath": {

     "$uid": { // where <uid> is the ID of the user obtained through Firebase Authentication
        ".write": "$uid === auth.uid"    
        ".read": true,

      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,直接给出uid

{
  "rules": {
    ".read": true,
    ".write": "auth.uid === 'dJrGShfgfd2'"
  }
}
Run Code Online (Sandbox Code Playgroud)