How can I use the default Google credentials on Heroku without a JSON file?

I am looking to deploy a Node application for Heroku, and the key task I came across is related to the default Google authorization workflow for Node. By default, Google searches for the JSON file with private keys, and the GOOGLE_APPLICATION_CREDENTIALSname of the environment variable indicating the path to this JSON file. This is normal for local development, but in production I naturally do not want to transfer this sensitive JSON file to the source code. Heroku allows you to create environment variables, but each variable is individual. Somehow I need to split this JSON file into separate variables, but I don’t know what to name them so that Google recognizes them.

There is a similar thread for Ruby, but the equivalent does not work in Node.

+4
source share
3 answers

A method getApplicationDefaultis simply a convenience for a factory to find the right customer. In fact, you create your client directly by passing parameters read from the environmental variables defined in Heroku .

Take this example that I used recently with a Heroku deployment:

const GoogleAuth = require('google-auth-library');

function authorize() {
    return new Promise(resolve => {
        const authFactory = new GoogleAuth();
        const jwtClient = new authFactory.JWT(
            process.env.GOOGLE_CLIENT_EMAIL, // defined in Heroku
            null,
            process.env.GOOGLE_PRIVATE_KEY, // defined in Heroku
            ['https://www.googleapis.com/auth/calendar']
        );

        jwtClient.authorize(() => resolve(jwtClient));
    });
}
+2
source

thank! I also found another solution if it helps others:

// Authentication on a global basis. var projectId = process.env.GCLOUD_PROJECT; // For example. 'Grape spaceship-123'

var gcloud = require ('google-cloud') ({projectId: projectId,

credentials: require ('./path/to/keyfile.json')

});

json-, auth

+1

When using api google translation I encountered the same problem. I was unable to reference the entire JSON file, so I created two env variables in Heroku and referenced them in the credential object. You cannot leave them alone. Private key replacement is an important detail. You must insert this full key, as on Heroku.

const Translate = require('@google-cloud/translate');
const projectId = 'your project id here';

const translate = new Translate({
  projectId: projectId,
  credentials: {
    private_key: process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'),
    client_email: process.env.GOOGLE_CLIENT_EMAIL
  }
});
+1
source

Source: https://habr.com/ru/post/1674803/


All Articles