This site has moved.
Here's how to use the default Apps Script authentication to connect to your Firebase database as an admin. This authentication method is only recommended for scripts running as yourself, not for add-ons or Apps Script web apps executed by end users (for that, please use the authentication via Service Account).
function updateData(userId, newUserData) {
var token = ScriptApp.getOAuthToken();
var fb = FirebaseApp.getDatabaseByUrl("https://my_db.firebaseio.com/", token);
fb.setData("users/" + userId, newUserData);
}
This authentication method is supported since v25 of the FirebaseApp library.
Note that Google offers several ways to authenticate to the Firebase Realtime Database via REST Requests:
https://firebase.google.com/docs/database/rest/auth
The FirebaseApp library for Apps Script was mostly compatible with Firebase legacy tokens. Those tokens aren't recommended by Google and aren't very secured. A better solution is to rely on a Service Account, the authentication method used in Firebase Admin SDK. Still, Service Account authentification relies on a Private Key that should never be shared ("Service account key files are very sensitive and you should never share them or store them on client devices."). Thus using the default Apps Script authentication can be a better way to perform admin operations on your database, without leaving any token / key visible in your code.
Make sure your Google account has at least an Editor role on your Firebase project. If you are the creator of your Firebase database, you do have the right permissions.
Update the manifest in your Apps Script project to authorize the Firebase service. By default, Apps Script automatically determines what scopes a script needs by scanning its code for function calls that require them. You can now add new scopes depending on your need:
https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes
Here's the scopes needed to access the Firebase Database Service:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/firebase.database
You will also need the following scope as FirebaseApp relies on the UrlFetchApp service to connect to your database:
https://www.googleapis.com/auth/script.external_request
Next time your run a function in your script, you will be prompted to authorize the Firebase service:
That's all, you can now use your script OAuth token (via the method ScriptApp.getOAuthToken()) to authenticate your calls to Firebase. Note that using this token gives you full access over your database, like the legacy token. Thus, your Firebase rules aren't taken into account.
function updateData(userId, newUserData) {
var token = ScriptApp.getOAuthToken();
var fb = FirebaseApp.getDatabaseByUrl("https://my_db.firebaseio.com/", token);
fb.setData("users/" + userId, newUserData);
}