javascript - 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)
}
},
解决方案
当您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 令牌。
推荐阅读
- python - 如何使用 Celery 顺序执行独立任务?
- c# - How to fix SQL order by issue with Crystal Report
- javascript - 为什么 GET 日期正确但在 POST 中不正确?
- c# - 如何制作可以迭代的 ApplicationUser 类型列表?
- json - How to navigate through a json file with Python 3? TypeError: list indices must be integers or slices, not str
- sql - GROUP BY and ORDER
- android - 如何在 Kotlin 中从活动中调用片段的方法并将数据同时发送到片段
- python - 我需要在同一个散点图中沿时间序列数据框绘制多个 y 变量
- mysql - 如何通过插入数据修复mysql错误
- vba - 根据用户通过复选框的选择生成 Word 文档的最佳方法是什么?