JWT-based authentication for server-to-server communication using service account credentials. This is ideal for backend services, automation, and any scenario that doesn't require user interaction.
Service account authentication using JSON Web Tokens.
/**
* JWT client for service account authentication
* Uses private key to create signed JWTs for API access
*/
class JWT extends AuthClient {
constructor(options?: JWTOptions);
/** Authorize and get access token */
authorize(): Promise<Credentials>;
/** Get access token */
getAccessToken(): Promise<{ token?: string | null; res?: GaxiosResponse }>;
/** Get headers for authenticated requests */
getRequestHeaders(): Promise<{ [key: string]: string }>;
/** Create scoped version of client */
createScoped(scopes: string | string[]): JWT;
/** Create delegated version for domain-wide delegation */
createScopedRequired(): boolean;
}
interface JWTOptions {
/** Service account email address */
email?: string;
/** Path to service account key file */
keyFile?: string;
/** Private key string */
key?: string;
/** Private key ID */
keyId?: string;
/** OAuth2 scopes to request */
scopes?: string | string[];
/** Subject for domain-wide delegation */
subject?: string;
/** Additional JWT claims */
additionalClaims?: { [key: string]: any };
/** Maximum token lifetime in seconds (default: 3600) */
maxTokenLifetimeS?: number;
/** Universe domain */
universeDomain?: string;
}
interface JWTInput {
/** Issuer (service account email) */
iss?: string;
/** Subject (user to impersonate for domain-wide delegation) */
sub?: string;
/** Audience (token endpoint URL) */
aud?: string;
/** Additional claims */
[key: string]: any;
}Usage Examples:
import { JWT } from "google-auth-library";
// Create JWT client with service account key file
const jwtClient = new JWT({
keyFile: '/path/to/service-account.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
// Authenticate and get access token
await jwtClient.authorize();
// Make authenticated request
const response = await jwtClient.request({
url: 'https://storage.googleapis.com/storage/v1/b',
params: { project: 'my-project' }
});
// Using private key directly
const jwtClient = new JWT({
email: 'service-account@project.iam.gserviceaccount.com',
key: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n',
scopes: ['https://www.googleapis.com/auth/bigquery']
});
// Domain-wide delegation (G Suite)
const jwtClient = new JWT({
keyFile: '/path/to/service-account.json',
subject: 'user@example.com', // User to impersonate
scopes: ['https://www.googleapis.com/auth/admin.directory.user']
});Self-signed JWT for direct API access without token exchange.
/**
* Self-signed JWT client for API access
* Creates JWTs that can be used directly as authentication
*/
class JWTAccess extends AuthClient {
constructor(email?: string, key?: string, keyId?: string, eagerRefreshThresholdMillis?: number);
/** Get request headers with JWT */
getRequestHeaders(uri?: string, additionalClaims?: Claims): Promise<{ [key: string]: string }>;
/** Get access token (returns JWT) */
getAccessToken(): Promise<{ token?: string | null; res?: GaxiosResponse }>;
/** Create signed JWT for specific audience */
createSignedJWT(claims: Claims): string;
}
interface Claims {
/** Issuer */
iss?: string;
/** Subject */
sub?: string;
/** Audience */
aud?: string;
/** Expiry time */
exp?: number;
/** Issued at time */
iat?: number;
/** Additional claims */
[key: string]: any;
}Usage Examples:
import { JWTAccess } from "google-auth-library";
// Create JWTAccess client
const jwtAccess = new JWTAccess(
'service-account@project.iam.gserviceaccount.com',
privateKey,
keyId
);
// Get headers for API request
const headers = await jwtAccess.getRequestHeaders(
'https://pubsub.googleapis.com/',
{ scope: 'https://www.googleapis.com/auth/pubsub' }
);
// Make request with JWT in Authorization header
const response = await fetch('https://pubsub.googleapis.com/v1/projects/my-project/topics', {
headers
});Authentication for Google Compute Engine using metadata service.
/**
* Authentication client for Google Compute Engine metadata service
* Retrieves access tokens from the metadata server for service accounts attached to compute resources
*/
class Compute extends OAuth2Client {
constructor(options?: ComputeOptions);
/** Service account email being used */
readonly serviceAccountEmail: string;
/** OAuth2 scopes configured for the client */
scopes: string[];
/** Fetch ID token from metadata service */
fetchIdToken(targetAudience: string): Promise<string>;
}
interface ComputeOptions extends OAuth2ClientOptions {
/** Service account email or 'default' */
serviceAccountEmail?: string;
/** OAuth2 scopes to request */
scopes?: string | string[];
}Usage Examples:
import { Compute } from "google-auth-library";
// Create Compute client (automatically detects GCE environment)
const computeClient = new Compute();
// Get access token from metadata service
const { token } = await computeClient.getAccessToken();
// Get project ID
const projectId = await computeClient.getProjectId();
// Check if running on GCE
const isGCE = await computeClient.isAvailable();
// Use specific service account
const computeClient = new Compute({
serviceAccountEmail: 'my-service-account@project.iam.gserviceaccount.com',
scopes: ['https://www.googleapis.com/auth/storage-full-control']
});Self-signed JWT client for direct API access without token exchange.
/**
* Self-signed JWT client for API access
* Creates JWTs that can be used directly as authentication without token exchange
*/
class JWTAccess {
constructor(
email?: string | null,
key?: string | null,
keyId?: string | null,
eagerRefreshThresholdMillis?: number
);
/** Service account email */
email?: string | null;
/** Private key for signing */
key?: string | null;
/** Private key ID */
keyId?: string | null;
/** Project ID */
projectId?: string;
/** Eager refresh threshold in milliseconds */
eagerRefreshThresholdMillis: number;
/** Get request headers with JWT */
getRequestHeaders(
url?: string,
additionalClaims?: Claims,
scopes?: string | string[]
): Headers;
/** Create JWTAccess credentials from JSON */
fromJSON(json: JWTInput): void;
/** Create JWTAccess credentials from stream */
fromStream(inputStream: ReadableStream): Promise<void>;
fromStream(inputStream: ReadableStream, callback: (err?: Error) => void): void;
}
interface Claims {
[index: string]: string;
}Usage Examples:
import { JWTAccess } from "google-auth-library";
// Create JWTAccess client
const jwtAccess = new JWTAccess(
'service-account@project.iam.gserviceaccount.com',
privateKey,
keyId
);
// Get headers for API request with audience-based JWT
const headers = jwtAccess.getRequestHeaders(
'https://pubsub.googleapis.com/',
{ scope: 'https://www.googleapis.com/auth/pubsub' }
);
// Make request with JWT in Authorization header
const response = await fetch('https://pubsub.googleapis.com/v1/projects/my-project/topics', {
headers
});
// Get headers for scoped JWT (useful for APIs that require OAuth scopes)
const scopedHeaders = jwtAccess.getRequestHeaders(
undefined,
undefined,
['https://www.googleapis.com/auth/cloud-platform']
);
// Create from service account JSON
const serviceAccountJson = {
client_email: 'service-account@project.iam.gserviceaccount.com',
private_key: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n',
private_key_id: 'key-id',
project_id: 'my-project'
};
jwtAccess.fromJSON(serviceAccountJson);/**
* Service account credential structure
*/
interface CredentialBody {
/** Service account email */
client_email?: string;
/** Client ID */
client_id?: string;
/** Private key */
private_key?: string;
/** Private key ID */
private_key_id?: string;
/** Project ID */
project_id?: string;
/** Credential type (usually 'service_account') */
type?: string;
/** Universe domain */
universe_domain?: string;
}
/**
* Generic credential request parameters
*/
interface CredentialRequest {
/** OAuth2 scopes */
scopes?: string[];
/** Request metadata */
request?: { [key: string]: string };
}/** Default authentication universe */
const DEFAULT_UNIVERSE = 'googleapis.com';
/** Client authentication methods */
enum ClientAuthentication {
REQUEST_BODY = 'request-body',
BASIC = 'basic'
}Common service account authentication errors:
try {
const jwtClient = new JWT({
keyFile: '/path/to/service-account.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
await jwtClient.authorize();
} catch (error) {
if (error.message.includes('invalid_grant')) {
console.error('Service account credentials are invalid or expired');
} else if (error.response?.status === 403) {
console.error('Service account lacks required permissions');
}
}