首页 > 解决方案 > Google Firebase RealtimeDB 规则不适用于 UID

问题描述

我们正在尝试为 google firebase realtimedb 编写规则,该规则仅允许用户在经过身份验证时读取和写入他们自己的 UID 的位置。这是我们目前的规则:

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

我们的数据库结构:

{
  "W48941DIDOIJ30" : {
    "subscription" : {
      "premium" : true
    },
    "watchlist" : []
  }
}

当我们尝试为具有相同 UID 的经过身份验证的用户发出监视列表或订阅请求时,我们会遇到 401 错误。是什么赋予了?

编辑:这是我们调用 realtimeDB 的方法(我们使用的是 NUXT.js)

async getData () {
      const messageRef = this.$fire.database.ref(this.currentUser.uid)
      const idToken = await this.currentUser.uid // or this.currentUser.getIdToken()
      const response = await axios.get(
        messageRef.toString() + '.json',
        {
          headers: { Authorization: `Bearer ${idToken}` }
        }
      )
      this.$store.commit('ON_WATCHLIST_CHANGE', response.data.watchlist)
      if (response.data.watchlist.companies.includes(this.$route.params.company) || response.data.watchlist.drugs.includes(this.$route.params.comound)) {
        this.$store.commit('CURRENT_PAGE_CHECK', true)
      }
    },

标签: javascriptfirebase-realtime-databasefirebase-security

解决方案


当您axios直接使用进行数据库调用时,您需要确保您也传递了用户的 ID 令牌:

async getData () {
  const messageRef = this.$fire.database.ref(this.currentUser.uid)
  const idToken = await this.$fire.auth.currentUser.getIdToken() // or this.currentUser.getIdToken()
  const response = await axios.get(
    messageRef.toString() + '.json',
    {
      headers: { 'Authorization': `Bearer ${idToken}` }
    }
  )
  this.$store.commit('ON_WATCHLIST_CHANGE', response.data.watchlist)
}

如果您省略令牌,Firebase 服务器只会将您视为匿名用户。

您还可以使用axios 拦截器来处理此问题,以便在每次发出请求时自动添加 ID 令牌。


推荐阅读