0

我们正在尝试为 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)
      }
    },

4

2 回答 2

1

当您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 令牌。

于 2021-10-24T05:24:38.937 回答
0

你能试试这个谷歌文档中也提到的规则结构,并检查它是否有效。

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

您也可以参考我发现的这个stackoverflow 线程,它可能很有用。

于 2021-10-25T15:38:23.293 回答