This site has moved.
Firebase legacy tokens are the easiest way to authenticate to your Firebase Realtime Database but are deprecated and not recommended by Google. They are still working but it is recommended to move to an authentication via Google OAuth2 access tokens.
If your Apps Script function is running as yourself, it is easier and more secure to authenticate via the default Apps Script access token. But if your script is deployed as an add-on or a web app executed by the user, you need to use a Service Account to generate a valid access token.
To generate an access token from a Service Account, best is to rely on the official OAuth2 for Apps Script library. You can then easily reuse the token in the getDatabaseByUrl() method of FirebaseApp:
function updateData(userId, newUserData) {
// generate an access token from a Service Account
// with the OAuth2 library
var token = getFirebaseService().getAccessToken();
// authenticated request to Firebase
var fb = FirebaseApp.getDatabaseByUrl("https://my_db.firebaseio.com/", token);
fb.setData("users/" + userId, newUserData);
}
A Service Account is automatically created for all Firebase projects. You need to retrieve the email address of your service account and a private key linked to that account.
Open your project in the Firebase Console and click on 'Project settings', then select the 'SERVICE ACCOUNTS' tab.
The service account email address (or client email) is directly visible. To retrieve the private key, click on the 'Generate New Private Key' button at the bottom of the page.
This will prompt you to download a JSON file on your computer. Open it with a text editor and copy the private key.
Here's a copy of the installation steps listed in the documentation of this library:
https://github.com/googlesamples/apps-script-oauth2#setup
Click on the menu item "Resources > Libraries..."
In the "Add a Library" text box, enter the script ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF and click the "Select" button.
Choose a version in the dropdown box (usually best to pick the latest version).
Click the "Save" button.
As indicated in the Firebase documentation, here are the required scopes to create a valid access token for Firebase:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/firebase.database
The OAuth2 library provides a code sample for the service account authorization flow available here:
https://github.com/googlesamples/apps-script-oauth2/blob/master/samples/GoogleServiceAccount.gs
Here's the code sample adapted to our use case:
var PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n';
var CLIENT_EMAIL = '...'; // service account email address
/**
* Authorizes and makes a request to the Firebase Realtime Database.
*/
function run(userId, newUserData) {
var service = getFirebaseService();
if (service.hasAccess()) {
var fb = FirebaseApp.getDatabaseByUrl("https://my_db.firebaseio.com/", service.getAccessToken());
fb.setData("users/" + userId, newUserData);
} else {
Logger.log(service.getLastError());
}
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
var service = getFirebaseService();
service.reset();
}
/**
* Configures the service.
*/
function getFirebaseService() {
return OAuth2.createService('Firebase')
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scopes.
.setScope('https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/firebase.database');
}
That's it. The OAuth2 library will generate a valid access token, save it under your Script Properties and refresh it when necessary. As stated in the Firebase documentation, the private key of your service account should never be shared. In the example above, it is saved directly as a global variable in the source code but you can decide to store it somewhere else (eg: in a Script Property).