【问题标题】:Restrict access to Firebase-Database with auth.uid not working使用 auth.uid 限制对 Firebase-Database 的访问不起作用
【发布时间】:2019-02-26 15:32:24
【问题描述】:

我想限制对我的 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 作为登录提供商。

【问题讨论】:

    标签: firebase firebase-realtime-database firebase-authentication google-authentication


    【解决方案1】:

    来自the documentation

    下面是一个规则示例,该规则授予已验证的写入权限 users 到/users/<uid>/,其中<uid> 是获取到的用户ID 通过 Firebase 身份验证。


    编辑:

    对于通过 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'"
      }
    }
    

    【讨论】:

    • 感谢您的回答。我不想授予一个用户访问特定路径的权限。我想实现一个用户可以写入所有数据。而其他人都做不到。这可能吗?
    • 那我必须把我的整个数据库包装到uid中吗?用户应该有类似管理员功能的东西
    • 在这种情况下,您也可以直接(以管理员身份)提供uid。检查弗兰克的答案:stackoverflow.com/a/41775839/4409113 更新了答案。
    • 好吧,我现在感觉真的很愚蠢...我切换到 axios 并忘记在我的补丁请求中发送 idToken...哦,奇怪:它是未经授权的...无论如何谢谢你 :)
    【解决方案2】:

    所有代码示例均正确

    所有代码片段,在 Mohsen 的问题和答案中 工作。 我只是忘记在我的补丁请求中发送 idToken。

    获取idToken的代码:

    firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
      // Send token to your backend via HTTPS
      // ...
    }).catch(function(error) {
      // Handle error
    });
    

    来自:https://firebase.google.com/docs/auth/admin/verify-id-tokens#retrieve_id_tokens_on_clients

    使用 idToken 进行身份验证:

    https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>
    

    来自:https://firebase.google.com/docs/database/rest/auth

    【讨论】:

    • 那我相信你应该接受我的回答,因为它是正确的。但是,你得到了我的解释。这将有助于未来的搜索:) 快乐编码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多