I have an app written on Firebase. Security rules and client side code aren\'t quite enough to make my app work. I need to connect a server to do a few tasks:
Updated (20160611): if you created your project on https://firebase.google.com, the steps access the database from a server are different. See this answer: Is it still possible to do server side verification of tokens in Firebase 3?
There are two ways that you can do this: Generate a server auth token, or use a Firebase secret.
Generate a server token You can use the same token generator libraries created for Custom Login to generate tokens that you can use from your server. You can then provide special access to this server from your security rules.
Here are the steps:
Generate a token with a pre-selected uid. If you're writing a node.js server, the code might look something like this:
var FirebaseTokenGenerator = require("firebase-token-generator");
var tokenGenerator = new FirebaseTokenGenerator("<your-firebase-secret>");
var token = tokenGenerator.createToken(
{uid: "my-awesome-server"},
{ expires: <far_into_the_future_seconds> });
Use the token to authenticate your client. Here's more node.js code:
var ref = new Firebase("https://<your-firebase>.firebaseio.com/");
ref.authWithCustomToken(token, function(error, authData) {
...
});
If there's no client for your server's language, e.g. PHP, use the token for your REST requests as the auth parameter.
Update your security rules to grant special permissions your server, as identified by the uid, like this simple rule that allows read access to the whole Firebase
{
"rules": {
".write": false,
".read": "auth.uid === 'my-awesome-server'"
}
}
Access all the data, do awesome stuff.
Advantages
Firebase secret
If you're the kind of developer who enjoys living on the edge, and types sudo at the drop of a hat, you can also authenticate using your Firebase secret directly.
But seriously, don't do this. It's dangerous.
Reasons not to do it
sudo
, it's incredibly dangerous.