Google Auto Authentication
google-auto-auth is a JavaScript library designed to simplify the process of authenticating requests to Google APIs. It abstracts away much of the complexity of managing credentials and obtaining access tokens, leveraging Google's Application Default Credentials (ADC) strategy to automatically find credentials based on the application's environment. This means it can seamlessly authenticate on Google Cloud Platform, when authenticated with the `gcloud` SDK, or via the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. For environments where automatic authentication isn't available, it supports explicit configuration using key files or credentials objects. The current stable version is `0.10.1`. While not on a rapid release cycle, it is actively maintained as a utility for streamlined Google API access, providing a thin layer over the `google-auth-library` to offer a more developer-friendly interface for common authentication patterns.
Common errors
-
TypeError: googleAutoAuth is not a constructor
cause Attempting to use the `new` keyword to instantiate the `google-auto-auth` client after v0.7.0.fixRemove the `new` keyword. Instead of `new googleAutoAuth()`, use `googleAutoAuth()`. -
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started to authenticate.
cause The library failed to automatically find credentials in the environment (e.g., not on GCP, `gcloud` not authenticated, `GOOGLE_APPLICATION_CREDENTIALS` not set or invalid).fixEnsure you are running on GCP, logged in via `gcloud auth application-default login`, or set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a valid service account key file path. Alternatively, provide credentials explicitly in `authConfig`. -
Error: MISSING_SCOPE
cause The API request requires specific OAuth scopes that were not provided in the `authConfig.scopes` array.fixReview the documentation for the Google API you are calling and add the necessary scope URLs (e.g., `https://www.googleapis.com/auth/cloud-platform`) to the `scopes` array in your `authConfig`.
Warnings
- breaking The `new` keyword is no longer supported when instantiating the `google-auto-auth` client. Direct invocation of the function (`googleAutoAuth({...})`) is now required.
- breaking Node.js version 4 or higher is now a strict requirement. Environments running older Node.js versions will not be supported.
- gotcha When `authorizeRequest` returns an error with `err.code = 'MISSING_SCOPE'`, it means the configured `authConfig.scopes` array does not include the necessary OAuth 2.0 scopes for the API you are trying to access.
- gotcha Automatic authentication relies on specific environmental conditions: running on Google Cloud Platform, being authenticated with the `gcloud` SDK, or having `GOOGLE_APPLICATION_CREDENTIALS` environment variable set to a valid JSON key file path. If these conditions are not met, explicit `authConfig` is required.
- gotcha Never embed service account private keys or full key file content directly in your source code, especially for public repositories. These are sensitive credentials.
Install
-
npm install google-auto-auth -
yarn add google-auto-auth -
pnpm add google-auto-auth
Imports
- googleAutoAuth
import googleAutoAuth from 'google-auto-auth';
const googleAutoAuth = require('google-auto-auth'); - AuthClient
const authClient = new googleAutoAuth(authConfig);
const authClient = googleAutoAuth(authConfig);
- authorizeRequest
googleAutoAuth.authorizeRequest(reqOpts, callback);
authClient.authorizeRequest(reqOpts, callback);
Quickstart
const googleAutoAuth = require('google-auto-auth');
const path = require('path');
// IMPORTANT: In a real application, never hardcode credentials or paths directly.
// Use environment variables or a secure configuration management system.
// For demonstration, we'll simulate a key file path.
process.env.GOOGLE_APPLICATION_CREDENTIALS = process.env.GOOGLE_APPLICATION_CREDENTIALS ?? path.join(__dirname, 'mock-key.json');
// If GOOGLE_APPLICATION_CREDENTIALS is not set or not valid, you must provide authConfig.
// Example with explicit credentials (replace with your actual data):
const authConfig = {
// keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS, // Path to a .json, .pem, or .p12 key file
// OR
// credentials: {
// client_email: process.env.GOOGLE_CLIENT_EMAIL ?? 'your-service-account@your-project.iam.gserviceaccount.com',
// private_key: process.env.GOOGLE_PRIVATE_KEY ?? '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n',
// },
scopes: ['https://www.googleapis.com/auth/cloud-platform'] // Required scopes for your API requests
};
// Create an auth client. It will automatically attempt to find credentials.
// If authConfig is empty and no default credentials are found, it might fail.
const auth = googleAutoAuth(authConfig);
// 1. Authorize an HTTP request object
auth.authorizeRequest({
method: 'GET',
uri: 'https://storage.googleapis.com/storage/v1/b'
}, (err, authorizedReqOpts) => {
if (err) {
console.error('Error authorizing request:', err.message);
// Handle specific errors like MISSING_SCOPE
if (err.code === 'MISSING_SCOPE') {
console.error('Missing required scopes. Please configure `authConfig.scopes`.');
}
return;
}
console.log('Authorized Request Options:', authorizedReqOpts);
// authorizedReqOpts now contains `headers: { Authorization: 'Bearer {{token}}' }`
});
// 2. Get an access token directly
auth.getToken((err, token) => {
if (err) {
console.error('Error getting token:', err.message);
return;
}
console.log('Access Token:', token ? token.substring(0, 20) + '...' : 'No token received');
});
// 3. Get the underlying google-auth-library client
auth.getAuthClient((err, client) => {
if (err) {
console.error('Error getting auth client:', err.message);
return;
}
console.log('Underlying google-auth-library client type:', client.constructor.name);
// You can interact with the google-auth-library client directly here if needed.
});