【问题标题】:Firebase, decoded idToken is not the same as the token sent with RESTFirebase,解码后的 idToken 与 REST 发送的令牌不一样
【发布时间】:2021-11-22 13:26:08
【问题描述】:

我正在为我的项目后端使用 firebase 实时数据库,但在制定安全规则时遇到了问题。我使用 REST 与数据库通信并授权 REST 请求,我根据https://firebase.google.com/docs/database/rest/auth 发送一个 idToken 作为“auth =”参数的查询。

Firebase 仅检测到我已获得授权,但当我比较数据库规则中的 auth.uid 时,它们并不相同。我设置了自己的服务器,如果我解码令牌,我发现它确实保存了用户的正确信息。

这是我想要实现但不起作用的数据库规则:

{
  "rules": {
      "$uid": {
        ".read": "auth.uid === $uid",
        ".write": "auth.uid === $uid"
      }
  }
} 

但这些规则确实有效,这意味着我已获得授权。为什么 auth 对象不保存实际的用户 ID,而是保存 auth.uid 的其他值?

  "rules": {
      "$uid": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
  }
}

为什么 firebase 对令牌的解码方式不同?我什至可以访问发送到规则的身份验证对象吗?

【问题讨论】:

    标签: node.js firebase firebase-realtime-database firebase-security


    【解决方案1】:

    auth 对象具有如下所列的 3 个属性:

    name description
    provider The authentication method used ("password", "anonymous", "facebook", "github", "google", or "twitter").
    uid A unique user id, guaranteed to be unique across all providers.
    token The contents of the Firebase Auth ID token. See the reference documentation for auth.token for more details.

    要访问包含自定义声明的解码令牌,您可以使用auth.token。您可以在documentation 中找到有关auth.token 对象的更多详细信息


    由于您的数据位于节点'data' 下,因此您必须在规则中指定:

    {
      "rules": {
        "data": {
          "$uid": {
            ".read": "auth.uid === $uid",
            ".write": "auth.uid === $uid"
          }
        }
      }
    } 
    

    【讨论】:

    • 有用的文档链接,但即使我使用以下规则,我仍然无法让它工作:“.read”:“auth.token.sub === $uid”。令牌中的 id 和我要读取的文件夹的名称不匹配...这可能是我在数据库中的数据结构中的问题吗?
    • @RomanKolar 您可以通过auth.uid 直接访问 UID,但请分享您数据库的屏幕截图
    • imgur.com/gallery/bgSsiDH,我尝试了“auth.uid === 'l51zB8vjPGc9QQ8DGNhUEfJSG7B3'”,这是我的 ID,它可以工作,但如果使用 $uid 就不行了吗?
    • @RomanKolar 您的规则没有为data 节点定义。它期望 UID 作为根键.. 你能分享完整的数据库结构,包括根节点吗?
    • 天哪,你是救世主...我正在阅读文档,我发誓它说根文件夹不必包含在规则中...非常感谢伙计,不敢相信我浪费了这么多时间... :)
    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2021-09-12
    • 2019-06-27
    • 2023-04-04
    • 2019-03-15
    相关资源
    最近更新 更多