How do you authenticate a server to Firebase?

天涯浪子 提交于 2019-11-27 00:05:31
mimming

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:

  1. Get the token generator library for your server's language / platform. Node.js and Java servers tend to work best.
  2. 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> });
    
  3. 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) {
      ...
    });
    
  4. If there's no client for your server's language, e.g. PHP, use the token for your REST requests as the auth parameter.

  5. 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'"
        }
    }
    
  6. Access all the data, do awesome stuff.

Advantages

  • This is Firebase's officially recommended way to authenticate your server.
  • Your server will respect validation rules.
  • The server is just another user. You can use security rules to provide fine grained access to your data.
  • Since access is fine grained, it's unlikely a bug in your server will cause damage, like delete your root node.

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

  • Just like blindly using sudo, it's incredibly dangerous.
  • Your server will not respect your validation rules.
  • Your server full read / write access to your Firebase. If it has an ugly enough bug, it might delete or corrupt data that is has no business accessing.
  • Your secret ends up in more places (potentially in outbound request logs, etc). You are exposed to more risk if it gets out.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!