Google Auto Authentication

0.10.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `google-auto-auth`, authorize an example API request, directly retrieve an access token, and access the underlying `google-auth-library` client. It highlights credential auto-discovery and explicit configuration.

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.
});

view raw JSON →