Comprehensive security system supporting SSL/TLS, OAuth2, metadata-based authentication, and custom credential providers for both channel-level and call-level authentication.
Central factory for creating all types of credentials with convenience methods for common security scenarios.
const credentials: {
/**
* Create insecure channel credentials (no encryption)
* @returns ChannelCredentials for insecure connections
*/
createInsecure(): ChannelCredentials;
/**
* Create SSL/TLS channel credentials
* @param rootCerts - Trusted root certificates (null for system default)
* @param privateKey - Client private key for mutual TLS
* @param certChain - Client certificate chain for mutual TLS
* @param verifyOptions - Additional verification options
* @returns ChannelCredentials for secure connections
*/
createSsl(
rootCerts?: Buffer | null,
privateKey?: Buffer | null,
certChain?: Buffer | null,
verifyOptions?: VerifyOptions
): ChannelCredentials;
/**
* Create SSL credentials from Node.js SecureContext
* @param secureContext - Pre-configured TLS secure context
* @param verifyOptions - Additional verification options
* @returns ChannelCredentials using the secure context
*/
createFromSecureContext(
secureContext: SecureContext,
verifyOptions?: VerifyOptions
): ChannelCredentials;
/**
* Combine channel credentials with call credentials
* @param channelCredentials - Base channel-level credentials
* @param callCredentials - Additional call-level credentials
* @returns Combined ChannelCredentials
*/
combineChannelCredentials(
channelCredentials: ChannelCredentials,
...callCredentials: CallCredentials[]
): ChannelCredentials;
/**
* Combine multiple call credentials into one
* @param first - First call credentials
* @param additional - Additional call credentials to combine
* @returns Combined CallCredentials
*/
combineCallCredentials(
first: CallCredentials,
...additional: CallCredentials[]
): CallCredentials;
/**
* Create call credentials from metadata generator function
* @param metadataGenerator - Function that generates authentication metadata
* @returns CallCredentials using the generator
*/
createFromMetadataGenerator(metadataGenerator: CallMetadataGenerator): CallCredentials;
/**
* Create call credentials from Google OAuth2 client
* @param googleCredential - Google OAuth2 client instance
* @returns CallCredentials using Google authentication
*/
createFromGoogleCredential(googleCredential: OAuth2Client): CallCredentials;
/**
* Create empty call credentials (no authentication)
* @returns Empty CallCredentials
*/
createEmpty(): CallCredentials;
};Channel-level credentials that secure the transport connection between client and server.
/**
* Abstract base class for channel-level security credentials
*/
abstract class ChannelCredentials {
/**
* Create insecure channel credentials (no encryption)
* @returns ChannelCredentials for plain HTTP/2 connections
*/
static createInsecure(): ChannelCredentials;
/**
* Create SSL/TLS channel credentials with optional mutual authentication
* @param rootCerts - Trusted CA certificates (null for system defaults)
* @param privateKey - Client private key for mutual TLS
* @param certChain - Client certificate chain for mutual TLS
* @param verifyOptions - Additional SSL verification options
* @returns ChannelCredentials for encrypted connections
*/
static createSsl(
rootCerts?: Buffer | null,
privateKey?: Buffer | null,
certChain?: Buffer | null,
verifyOptions?: VerifyOptions
): ChannelCredentials;
/**
* Create credentials from an existing SecureContext
* @param secureContext - Pre-configured TLS context
* @param verifyOptions - Additional verification options
* @returns ChannelCredentials using the context
*/
static createFromSecureContext(
secureContext: SecureContext,
verifyOptions?: VerifyOptions
): ChannelCredentials;
/**
* Combine with call credentials to create composite credentials
* @param callCredentials - Call-level credentials to add
* @returns New ChannelCredentials with call credentials attached
*/
compose(callCredentials: CallCredentials): ChannelCredentials;
}Options for customizing SSL/TLS certificate verification behavior.
interface VerifyOptions {
/** Custom server name for SNI and certificate verification */
checkServerIdentity?: CheckServerIdentityCallback;
}
/**
* Custom server identity verification callback
* @param hostname - Expected hostname
* @param cert - Server certificate
* @returns Error if verification fails, undefined if success
*/
type CheckServerIdentityCallback = (hostname: string, cert: any) => Error | undefined;SSL Credentials Examples:
import { credentials } from "@grpc/grpc-js";
import * as fs from "fs";
// Insecure credentials (development only)
const insecure = credentials.createInsecure();
// Basic SSL with system root certificates
const basicSsl = credentials.createSsl();
// SSL with custom root certificates
const customSsl = credentials.createSsl(
fs.readFileSync("ca-cert.pem")
);
// Mutual TLS with client certificates
const mutualTls = credentials.createSsl(
fs.readFileSync("ca-cert.pem"), // Root CA
fs.readFileSync("client-key.pem"), // Client private key
fs.readFileSync("client-cert.pem") // Client certificate
);
// SSL with custom server identity verification
const customVerification = credentials.createSsl(
null, // Use system roots
null,
null,
{
checkServerIdentity: (hostname, cert) => {
console.log(`Verifying certificate for ${hostname}`);
// Custom verification logic
return undefined; // No error = success
}
}
);Call-level credentials that add authentication information to individual RPC calls.
/**
* Abstract base class for call-level authentication credentials
*/
abstract class CallCredentials {
/**
* Create call credentials from a metadata generator function
* @param metadataGenerator - Function that generates auth metadata
* @returns CallCredentials using the generator
*/
static createFromMetadataGenerator(metadataGenerator: CallMetadataGenerator): CallCredentials;
/**
* Create call credentials from Google OAuth2 client
* @param googleCredential - Google OAuth2 client
* @returns CallCredentials for Google services
*/
static createFromGoogleCredential(googleCredential: OAuth2Client): CallCredentials;
/**
* Create empty call credentials (no authentication)
* @returns Empty CallCredentials
*/
static createEmpty(): CallCredentials;
/**
* Combine with another call credentials
* @param other - Additional call credentials to combine
* @returns New CallCredentials with both credentials
*/
compose(other: CallCredentials): CallCredentials;
}Function interface for generating authentication metadata dynamically.
/**
* Function that generates authentication metadata for calls
* @param options - Call context and options
* @param callback - Called with generated metadata or error
*/
type CallMetadataGenerator = (
options: CallMetadataOptions,
callback: (error: Error | null, metadata?: Metadata) => void
) => void;
interface CallMetadataOptions {
/** Service URL being called */
service_url: string;
/** Method name being called */
method_name: string;
}Call Credentials Examples:
import { credentials, Metadata } from "@grpc/grpc-js";
// JWT token authentication
const jwtCredentials = credentials.createFromMetadataGenerator(
(options, callback) => {
const token = getJwtToken(); // Your token retrieval logic
const metadata = new Metadata();
metadata.add('authorization', `Bearer ${token}`);
callback(null, metadata);
}
);
// API key authentication
const apiKeyCredentials = credentials.createFromMetadataGenerator(
(options, callback) => {
const metadata = new Metadata();
metadata.add('x-api-key', process.env.API_KEY!);
callback(null, metadata);
}
);
// Google OAuth2 authentication
const googleAuth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
const googleCredentials = credentials.createFromGoogleCredential(
await googleAuth.getClient()
);
// Combine multiple call credentials
const combinedCallCreds = credentials.combineCallCredentials(
jwtCredentials,
apiKeyCredentials
);
// Combine channel and call credentials
const finalCredentials = credentials.combineChannelCredentials(
credentials.createSsl(),
combinedCallCreds
);Server-side credentials for accepting secure connections and authenticating clients.
/**
* Abstract base class for server-side credentials
*/
abstract class ServerCredentials {
/**
* Create insecure server credentials (no encryption)
* @returns ServerCredentials for plain HTTP/2
*/
static createInsecure(): ServerCredentials;
/**
* Create SSL/TLS server credentials
* @param rootCerts - Trusted client CA certificates for client auth
* @param keyCertPairs - Server private key and certificate pairs
* @param checkClientCertificate - Whether to require client certificates
* @returns ServerCredentials for encrypted connections
*/
static createSsl(
rootCerts: Buffer | null,
keyCertPairs: KeyCertPair[],
checkClientCertificate?: boolean
): ServerCredentials;
}Interface for server private keys and certificates.
interface KeyCertPair {
/** Server private key in PEM format */
private_key: Buffer;
/** Server certificate chain in PEM format */
cert_chain: Buffer;
}Server Credentials Examples:
import { ServerCredentials } from "@grpc/grpc-js";
import * as fs from "fs";
// Insecure server (development only)
const insecureServer = ServerCredentials.createInsecure();
// SSL server with certificate
const sslServer = ServerCredentials.createSsl(
null, // No client certificate validation
[{
private_key: fs.readFileSync("server-key.pem"),
cert_chain: fs.readFileSync("server-cert.pem")
}]
);
// SSL server with client certificate validation
const mutualTlsServer = ServerCredentials.createSsl(
fs.readFileSync("client-ca.pem"), // Trusted client CAs
[{
private_key: fs.readFileSync("server-key.pem"),
cert_chain: fs.readFileSync("server-cert.pem")
}],
true // Require client certificates
);
// Multiple certificate pairs (SNI support)
const multiCertServer = ServerCredentials.createSsl(
null,
[
{
private_key: fs.readFileSync("example.com-key.pem"),
cert_chain: fs.readFileSync("example.com-cert.pem")
},
{
private_key: fs.readFileSync("api.example.com-key.pem"),
cert_chain: fs.readFileSync("api.example.com-cert.pem")
}
]
);Interface for Google OAuth2 clients used with call credentials.
/**
* OAuth2 client interface for Google authentication
*/
interface OAuth2Client {
/** Get access token for authentication */
getAccessToken(): Promise<{ token?: string | null; res?: any }>;
/** Request metadata for gRPC calls */
getRequestMetadata(url: string): Promise<{ [key: string]: string }>;
}Internal types used by the credentials system for connection establishment.
interface SecureConnector {
/** Connect securely to the target */
connect(deadline: Date): Promise<SecureConnectResult>;
}
interface SecureConnectResult {
/** The established connection */
connection: any;
/** Connection security information */
connectedAddress?: any;
}Complex credential scenarios combining multiple authentication methods.
Advanced Usage Example:
import { credentials, Metadata, ServerCredentials } from "@grpc/grpc-js";
// Client-side: Complex credential chain
const clientCreds = credentials.combineChannelCredentials(
// Base SSL with custom verification
credentials.createSsl(
fs.readFileSync("ca-cert.pem"),
fs.readFileSync("client-key.pem"),
fs.readFileSync("client-cert.pem"),
{
checkServerIdentity: (hostname, cert) => {
// Custom verification logic
console.log(`Verifying ${hostname}`);
return undefined;
}
}
),
// JWT authentication
credentials.createFromMetadataGenerator((options, callback) => {
const metadata = new Metadata();
metadata.add('authorization', `Bearer ${getJwtToken()}`);
metadata.add('x-client-version', '1.0.0');
callback(null, metadata);
}),
// API key authentication
credentials.createFromMetadataGenerator((options, callback) => {
const metadata = new Metadata();
metadata.add('x-api-key', process.env.API_KEY!);
callback(null, metadata);
})
);
// Server-side: SSL with client validation
const serverCreds = ServerCredentials.createSsl(
fs.readFileSync("client-ca.pem"), // Trust these client CAs
[{
private_key: fs.readFileSync("server-key.pem"),
cert_chain: fs.readFileSync("server-cert.pem")
}],
true // Require and validate client certificates
);