I want to restrict access to my Firebase Database, so that only the users I authorize can write to it. But the solution almost everywhere proposed doesn't seem to work for me.
I always get an 401 (unathorized) Error in my Console.
I tried two ways of checking wheter the right user is logged in or not, but none of them worked for me.:
1. uid hard-coded in rules:
{
"rules": {
".read": true,
".write": "auth.uid === 'UID'")",
}
}
2. uid in database
{
"rules": {
".read": true,
".write": "root.child('users').hasChild(auth.uid)",
}
}
In both ways I used the uid provided in the Firebase-Authentication overview. I use Google as Signin provider.
No its safe to use the uid and recommended, firebase uses auth to authenticate the user and the assign the uid to identify the user across firebase. You will be using uid in your security rules and as well as to identify user info in your db records.
UIDs in firebase are UUIDs as well. UIDs are nowadays indeed UUIDs.
Any Firebase Realtime Database URL is accessible as a REST endpoint. All we need to do is append . json to the end of the URL and send a request from our favorite HTTPS client and we can access the data. It was confirmed that this Firebase Realtime Database URL is accessible without authentication.
From the documentation:
Here's an example of a rule that grants write access for authenticated users to
/users/<uid>/
, where<uid>
is the ID of the user obtained through Firebase Authentication.
Edit:
For a specific path and current obtained user through Firebase Authentication, this should help:
{
"rules": {
"YourSpecificPath": {
"$uid": { // where <uid> is the ID of the user obtained through Firebase Authentication
".write": "$uid === auth.uid"
".read": true,
}
}
}
}
Or, give the uid
directly:
{
"rules": {
".read": true,
".write": "auth.uid === 'dJrGShfgfd2'"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With