首页 > 解决方案 > 使用 auth.uid 限制对 Firebase-Database 的访问不起作用

问题描述

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

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

我尝试了两种检查正确用户是否登录的方法,但它们都不适合我:

1. uid 硬编码在规则中:

{
"rules": {
  ".read": true,
  ".write": "auth.uid === 'UID'")",
    }
}

2. 数据库中的uid

{
"rules": {
  ".read": true,
  ".write": "root.child('users').hasChild(auth.uid)",
    }
}

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

标签: firebasefirebase-realtime-databasefirebase-authenticationgoogle-authentication

解决方案


文档中

下面是一个规则示例,该规则授予经过身份验证的用户对 的写入权限/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,

      }
    }
  }
}

或者,uid直接给出:

{
  "rules": {
    ".read": true,
    ".write": "auth.uid === 'dJrGShfgfd2'"
  }
}

推荐阅读