首页 > 解决方案 > 无法使用自定义令牌访问 firebase 数据库

问题描述

出于某种原因,当我测试我的数据库访问规则时,它在 firebase 模拟器上运行良好。但是当我在我的代码上尝试它时它不起作用,该值永远不会返回。如果我更改规则以允许像下面这样进行全局读取,则代码将再次开始工作。

{
  "rules": {
    ".read":"true"
   }
}

所以我相信错误不在规则本身,而是在身份验证过程中的某个时刻。最奇怪的部分是当我跑步时

firebase.auth().currentUser.uid

它返回预期值

"0x17d54a755b1bccbe23c6834a38f511c055e67a71"

我已经检查了文档

https://firebase.google.com/docs/database/security/securing-data https://firebase.google.com/docs/auth/admin/create-custom-tokens

但我没能找到问题

这些是访问规则。

{
  "rules": {
    "NFC":{
      "$mainProductKey":{
        ".write":"root.child('brands').child(auth.uid).child($mainProductKey).exists()"
      },
      ".write":"root.child('brands').child(auth.uid).child('products').exists()",
      ".read":"true"
    },
    "brands":{
      "$uid":{
        ".read": "$uid == auth.uid",
        ".write": "$uid == auth.uid"
      }
    },
  }
}

这是我的数据库结构的一部分

{
  "NFC" : {
    ...
  },
  "brands" : {
    "0x17d54A755b1BCcBe23C6834A38F511c055e67a71" : {
      "unlocked" : true
    }
  }
}

这是我的 JWT 令牌有效负载

{
  "uid": "0x17d54a755b1bccbe23c6834a38f511c055e67a71",
  "iat": 1536771364,
  "exp": 1536774964,
  "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
  "iss": "firebase-adminsdk-u3222@deverytest-3d280.iam.gserviceaccount.com",
  "sub": "firebase-adminsdk-u3222@deverytest-3d280.iam.gserviceaccount.com"
}

这是我添加规则后没有返回的代码

export function loadAccountLock (brandAddress) {
  return new Promise((resolve, reject) => {
    firebase.database().ref(`brands/${brandAddress}/`).once('value', function (snapshot) {
      let brand = snapshot.val() || {}
      resolve(!!brand.unlocked)
    })
  })
}

这就是我验证用户的方式

firebase.auth().signInWithCustomToken(token)

标签: javascriptfirebasefirebase-realtime-databasefirebase-authenticationfirebase-security

解决方案


我弄清楚了问题所在。实际上,我在令牌内发送了小写的以太坊地址,但我在数据库中的密钥是大写的。由于 firebase 规则区分大小写,因此我获得了被拒绝的读取权限。

简而言之,规则或身份验证码没有问题


推荐阅读