Search code examples
google-apifirebase-hostinggoogle-api-nodejs-client

How to get an access_token from googleapis?


I am trying to get an access token for accessing the Firebase Hosting API from a Service account, as described here.
The code below does not return an access_token, but an id_token instead, which fails to authenticate when trying to use the API.
What am I doing wrong? How can I obtain an access token?

const { google } = require("googleapis");

var serviceAccount = require("../functions/src/services/serviceAccountKey.json");

async function getAccessToken() {
    try {
        const jwtClient = new google.auth.JWT(
            serviceAccount.client_email,
            null,
            serviceAccount.private_key,
            ["firebasehosting.googleapis.com"],
            null
        );
        const credentials = await jwtClient.authorize();
        console.log(credentials);
    } catch (error) {
        console.log(error);
    }
}

getAccessToken();

It returns a credentials object:

{
  access_token: undefined,
  token_type: 'Bearer',
  expiry_date: undefined,
  id_token: '...', // edited out
  refresh_token: 'jwt-placeholder'
}

Solution

  • For the record, I finally got it.
    My token scope was invalid: I should use https://www.googleapis.com/auth/firebase
    The valid scopes are listed here