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