I can't seem to get my database rules to work, when they require authentication.
The user is logged in using JavaScript, and then the database is updated via PHP / REST request using firebase-php.
PHP:
$firebase = new \Firebase\FirebaseLib('https://AppNameGoesHere.firebaseio.com/');
$data = array(
'field1' => $response_array['field1'],
'field2' => $response_array['field2'],
'field3' => $response_array['field3']
);
$firebase->set('users/' . $response_array['userID'], $data)
The $response_array
is an array from an HTML form. $response_array['userID']
is the Firebase user uid.
These rules work (no auth):
{
"rules": {
"users": {
"$uid": {
".read": true,
".write": true
}
}
}
}
These, with auth, don't work:
{
"rules": {
"users": {
"$uid": {
".read": "auth.uid === $uid",
".write": "auth.uid === $uid"
}
}
}
}
Error:
{ "error" : "Permission denied" }
Any suggestions?
As Frank mentioned in the comments, you must call setToken()
in order to authenticate all subsequent database reads/writes. To get that token from the client-side JavaScript and pass it to your PHP endpoint, you should use getIdToken like so:
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your PHP backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
With that idToken
value, it looks like you can pass that along to the firebase-php
library's setToken
function:
...
$firebase->setToken(idToken)
$firebase->set('users/' . $response_array['userID'], $data)
As long as $response_array['userID']
matches up with the uid of whoever makes that request, you should no longer receive the Permission denied
error.