We are trying to write rules for a google firebase realtimedb that only allows users to read and write to a location that is their own UID when they are authenticated. Here is our current rules:
{
"rules": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
}
}
And our DB structure:
{
"W48941DIDOIJ30" : {
"subscription" : {
"premium" : true
},
"watchlist" : []
}
}
When we attempt to make a get request for the watchlist or subscription for an authenticated user with the same UID we are hit with a 401 error. What gives?
Edit: Here is our method that calls the realtimeDB (we are using 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)
}
},
When you make a database call using axios directly, you need to make sure that you pass in your user's ID token too:
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)
}
If you omit the token, you'll just be considered an anonymous user by the Firebase servers.
You can also handle this using an axios interceptor to automatically add the ID token each time a request is made.
can you try this below structure for your rules which is also mentioned in this Google document and check if it works.
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid", ".read": "auth.uid == $uid"
}
}
}
}
You can also refer to this stackoverflow thread that I found, which might be useful.