Skip to content

Authentication

When using the Route Optimization API in production, you need to authenticate with Google Cloud. This guide covers all authentication methods supported by RouteCalculator.

Overview

RouteCalculator supports three authentication methods:

  1. API Key - Simplest method, recommended for getting started
  2. Service Account - More secure, recommended for production
  3. Mock Mode - No authentication needed, for testing only

Authentication Methods

API Key authentication is the simplest way to get started with the Route Optimization API.

Setup

  1. Go to Google Cloud Console Credentials
  2. Click "Create Credentials" > "API Key"
  3. Copy the generated API key
  4. (Recommended) Click "Restrict Key" to add security restrictions

Usage

typescript
import { RouteCalculator } from '@route-optimization/core';

const calculator = new RouteCalculator({
  projectId: 'your-project-id',
  apiKey: 'AIzaSyC...your-api-key',
  debug: true,
});

await calculator.initialize();

Pros & Cons

Pros:

  • ✅ Simple setup process
  • ✅ No file management needed
  • ✅ Easy to rotate and update
  • ✅ Works well in serverless environments

Cons:

  • ⚠️ Less granular permission control
  • ⚠️ Should be restricted to specific APIs
  • ⚠️ Needs proper secret management

Security Best Practices

  1. Restrict the API Key:

    - Set application restrictions (HTTP referrers, IP addresses, etc.)
    - Restrict to only "Cloud Optimization API"
  2. Store Securely:

    • Never commit API keys to version control
    • Use environment variables
    • Use secret management services (AWS Secrets Manager, etc.)
  3. Rotate Regularly:

    • Change API keys periodically
    • Have a rotation policy in place

Environment Variables

typescript
// .env file
GOOGLE_PROJECT_ID=your-project-id
GOOGLE_API_KEY=AIzaSyC...your-api-key

// In your code
const calculator = new RouteCalculator({
  projectId: process.env.GOOGLE_PROJECT_ID,
  apiKey: process.env.GOOGLE_API_KEY,
});

Service Account provides more secure authentication with granular IAM permissions.

Setup

  1. Go to IAM & Admin > Service Accounts
  2. Click "Create Service Account"
  3. Name it (e.g., "route-optimizer")
  4. Click "Create and Continue"
  5. Grant role: "Cloud Optimization API User"
  6. Click "Done"
  7. Click on the created service account
  8. Go to "Keys" tab
  9. Click "Add Key" > "Create new key"
  10. Choose JSON format
  11. Save the downloaded file securely

Usage with File Path

typescript
import { RouteCalculator } from '@route-optimization/core';

const calculator = new RouteCalculator({
  projectId: 'your-project-id',
  credentialsPath: './service-account-key.json',
  debug: true,
});

await calculator.initialize();

Usage with Credentials Object

typescript
import { RouteCalculator } from '@route-optimization/core';
import serviceAccountKey from './service-account-key.json';

const calculator = new RouteCalculator({
  projectId: 'your-project-id',
  credentials: serviceAccountKey,
});

await calculator.initialize();

Usage with Environment Variable

typescript
import { RouteCalculator } from '@route-optimization/core';

// Set environment variable: GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
const calculator = new RouteCalculator({
  projectId: 'your-project-id',
  // No credentials needed - will use GOOGLE_APPLICATION_CREDENTIALS
});

await calculator.initialize();

Pros & Cons

Pros:

  • ✅ More secure than API keys
  • ✅ Granular IAM permissions
  • ✅ Better audit trail
  • ✅ Supports role-based access control
  • ✅ Can be used with Workload Identity Federation

Cons:

  • ⚠️ More complex setup
  • ⚠️ File management required
  • ⚠️ JSON file must be kept secure

Security Best Practices

  1. Principle of Least Privilege:

    • Only grant "Cloud Optimization API User" role
    • Don't use Owner or Editor roles
  2. Secure Storage:

    • Never commit service account keys to Git
    • Use .gitignore to exclude key files
    • Store in secure secret management systems
  3. Key Rotation:

    • Rotate keys regularly (every 90 days recommended)
    • Maintain multiple active keys during rotation
    • Delete old keys after rotation
  4. Monitor Usage:

    • Enable Cloud Audit Logs
    • Monitor for unusual API usage
    • Set up alerts for security events

Mock Mode (Development & Testing)

Mock mode allows testing without any Google Cloud setup or authentication.

Usage

typescript
import { RouteCalculator } from '@route-optimization/core';

const calculator = new RouteCalculator({
  useMockMode: true,
  debug: true,
});

await calculator.initialize(); // No authentication needed

Features

  • ✅ No API key or credentials required
  • ✅ No billing charges
  • ✅ Instant responses
  • ✅ Deterministic results for testing
  • ❌ Simplified optimization algorithm
  • ❌ No real-world traffic data

When to Use

  • Local development
  • Unit testing
  • Integration testing
  • CI/CD pipelines
  • Demos and prototypes

Comparison Table

FeatureAPI KeyService AccountMock Mode
Setup ComplexityLowMediumNone
SecurityMediumHighN/A
CostPaidPaidFree
IAM IntegrationLimitedFullN/A
Audit TrailBasicCompleteN/A
Best ForQuick start, small appsProduction, enterpriseDevelopment, testing

Troubleshooting

API Key Issues

Error: "API key not valid"

Cause: API key is incorrect or has been deleted.

Solution:

  1. Verify the API key is correct
  2. Check if the key still exists in Google Cloud Console
  3. Generate a new API key if needed

Error: "API keys are not supported by this API"

Cause: Some Google APIs don't support API key authentication.

Solution:

  1. Use Service Account authentication instead
  2. Check if the API supports API keys

Error: "API key has been restricted"

Cause: API key restrictions are blocking the request.

Solution:

  1. Check API restrictions in Cloud Console
  2. Ensure "Cloud Optimization API" is allowed
  3. Verify IP/referrer restrictions match your setup

Service Account Issues

Error: "Could not load the default credentials"

Cause: Service account credentials are not found or invalid.

Solution:

  1. Verify credentialsPath points to correct file
  2. Check file permissions (readable by your app)
  3. Ensure JSON file is valid format
  4. Try setting GOOGLE_APPLICATION_CREDENTIALS environment variable

Error: "Permission denied"

Cause: Service account lacks required permissions.

Solution:

  1. Go to IAM & Admin in Cloud Console
  2. Find your service account
  3. Add role: "Cloud Optimization API User"
  4. Wait a few minutes for permissions to propagate

Error: "Service account key is expired"

Cause: The service account key has been deleted or expired.

Solution:

  1. Create a new service account key
  2. Update your application with new credentials
  3. Delete the old key

Best Practices Summary

Development

typescript
// Use mock mode for local development
const calculator = new RouteCalculator({
  useMockMode: true,
  debug: true,
});

Testing

typescript
// Use mock mode for tests
const calculator = new RouteCalculator({
  useMockMode: true,
});

Staging

typescript
// Use API Key with environment variables
const calculator = new RouteCalculator({
  projectId: process.env.GOOGLE_PROJECT_ID,
  apiKey: process.env.GOOGLE_API_KEY,
  debug: true,
});

Production

typescript
// Use Service Account with secure storage
const calculator = new RouteCalculator({
  projectId: process.env.GOOGLE_PROJECT_ID,
  credentialsPath: process.env.GOOGLE_CREDENTIALS_PATH,
  debug: false, // Disable debug logging in production
});

Next Steps

References

Released under the MIT License.