How can I check if Google Cloud is logged in with Nodejs?

80 Views Asked by At

If I log in to Google Cloud with gcloud-init, it appears that everything is successful. But I also want to check programmatically if I am successfully authenticated, and if not, halt the program. I tried the following code, which I thought was working and outputs the project ID to the console:

import { GoogleAuth } from 'google-auth-library';

async function checkGoogleAuth() {
  try {
    const auth = new GoogleAuth({
      scopes: 'https://www.googleapis.com/auth/cloudkms',
    });
    const projectId = await auth.getProjectId();
    console.log(`  Google Auth Project ID: ${projectId}`);
  } catch (err: any) {
    throw new Error(`Google Auth Error: ${err.message}`);
  }
}

However, when I try to use the @google-cloud/kms library, I get the error:

Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.

To get it to work, I need to execute:

$ gcloud auth application-default login

How can I check programmatically if I am successfully authenticated with Google Cloud and that the credentials can be loaded?

1

There are 1 best solutions below

0
Mike On

Ok, I think I was able to figure it out. Instead of importing google-auth-library, you can import @google-cloud/kms and attempt to get the project ID and the access control policy. Both of these throw errors if they fail.

import KMS from '@google-cloud/kms';

async function checkGoogleAuth() {
  try {
    const kms = new KMS.KeyManagementServiceClient();

    const projectId = await kms.getProjectId();

    const formattedResource = kms.keyRingPath(
      process.env.GCLOUD_PROJECT_ID || '',
      process.env.GCLOUD_KMS_LOCATION || '',
      process.env.GCLOUD_KMS_KEY_RING || ''
    );
    await kms.getIamPolicy({
      resource: formattedResource,
    } as any);

    console.log(`  Google Auth Project ID: ${projectId}`);
  } catch (err: any) {
    console.error(`Google Auth Error: ${err.message}`);
    process.exit(1);
  }
}