Google Firebase RealtimeDB规则与UID不工作



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

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

和我们的DB结构:

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

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

编辑:下面是我们调用realtimeDB的方法(我们使用nuext .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)
}
},

当您直接使用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令牌。

你可以尝试下面的结构为你的规则,也在这个谷歌文档中提到,并检查它是否有效。

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

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

最新更新