or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-authentication-flows.mddefault-authentication.mddeveloper-tool-authentication.mdindex.mdinteractive-authentication.mdmanaged-identity-authentication.mdservice-principal-authentication.mdtoken-provider-integration.md
tile.json

service-principal-authentication.mddocs/

Service Principal Authentication

Service principal authentication enables automated authentication using Azure AD application registrations. This approach is ideal for production applications, automated scripts, and scenarios where interactive authentication is not possible.

Capabilities

Client Secret Authentication

Authenticate using a service principal with a client secret. This is the most common service principal authentication method.

/**
 * Enables authentication to Microsoft Entra ID using a client secret
 * that was generated for an app registration
 */
class ClientSecretCredential implements TokenCredential {
  constructor(tenantId: string, clientId: string, clientSecret: string, options?: ClientSecretCredentialOptions);
  getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken>;
}

interface ClientSecretCredentialOptions extends TokenCredentialOptions {
  /**
   * Allows specification of additional tenant IDs for multi-tenant authentication
   */
  additionallyAllowedTenants?: string[];
  
  /**
   * Disable instance discovery for sovereign clouds
   */
  disableInstanceDiscovery?: boolean;
}

Usage Examples:

import { ClientSecretCredential } from "@azure/identity";
import { KeyClient } from "@azure/keyvault-keys";

// Basic client secret authentication
const credential = new ClientSecretCredential(
  "12345678-1234-1234-1234-123456789012", // tenant ID
  "12345678-1234-1234-1234-123456789012", // client ID  
  "your-client-secret"                     // client secret
);

// Use with Azure SDK client
const client = new KeyClient("https://vault.vault.azure.net", credential);

// With additional configuration
const credentialWithOptions = new ClientSecretCredential(
  tenantId,
  clientId,
  clientSecret,
  {
    authorityHost: "https://login.microsoftonline.us", // for government cloud
    additionallyAllowedTenants: ["other-tenant-id"]
  }
);

Client Certificate Authentication

Authenticate using a service principal with a client certificate. More secure than client secrets as certificates can have shorter lifespans and are harder to accidentally expose.

/**
 * Enables authentication to Microsoft Entra ID using a PFX or PEM certificate
 * that was configured for an app registration
 */
class ClientCertificateCredential implements TokenCredential {
  constructor(
    tenantId: string, 
    clientId: string, 
    certificatePath: string, 
    options?: ClientCertificateCredentialOptions
  );
  constructor(
    tenantId: string,
    clientId: string, 
    configuration: ClientCertificateCredentialPEMConfiguration,
    options?: ClientCertificateCredentialOptions
  );
  getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken>;
}

interface ClientCertificateCredentialOptions extends TokenCredentialOptions {
  /**
   * Option to include x5c header which contains the public certificate
   */
  sendCertificateChain?: boolean;
  
  /**
   * Password for the certificate file (if encrypted)
   */
  certificatePassword?: string;
  
  /**
   * Allows specification of additional tenant IDs for multi-tenant authentication
   */
  additionallyAllowedTenants?: string[];
}

interface ClientCertificateCredentialPEMConfiguration {
  /**
   * PEM-encoded certificate content
   */
  certificate: string;
  
  /**
   * PEM-encoded private key content
   */
  certificateKey: string;
  
  /**
   * Optional passphrase for the private key
   */
  certificateKeyPassword?: string;
}

// Type aliases for certificate configuration
type ClientCertificatePEMCertificatePath = string;
type ClientCertificatePEMCertificate = ClientCertificateCredentialPEMConfiguration;

Usage Examples:

import { ClientCertificateCredential } from "@azure/identity";

// Using certificate file path
const credentialFromFile = new ClientCertificateCredential(
  tenantId,
  clientId,
  "/path/to/certificate.pem",
  {
    sendCertificateChain: true,
    certificatePassword: "cert-password" // if certificate is encrypted
  }
);

// Using certificate content directly
const credentialFromContent = new ClientCertificateCredential(
  tenantId,
  clientId,
  {
    certificate: "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----",
    certificateKey: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",
    certificateKeyPassword: "key-password" // if private key is encrypted
  }
);

// Using PFX certificate
const credentialPfx = new ClientCertificateCredential(
  tenantId,
  clientId,
  "/path/to/certificate.pfx",
  {
    certificatePassword: "pfx-password"
  }
);

Client Assertion Authentication

Authenticate using a service principal with a custom client assertion. This allows for advanced scenarios where you generate your own JWT assertions.

/**
 * Authenticates a service principal with a JWT assertion
 */
class ClientAssertionCredential implements TokenCredential {
  constructor(
    tenantId: string,
    clientId: string, 
    getAssertion: () => string,
    options?: ClientAssertionCredentialOptions
  );
  getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken>;
}

interface ClientAssertionCredentialOptions extends TokenCredentialOptions {
  /**
   * Allows specification of additional tenant IDs for multi-tenant authentication
   */
  additionallyAllowedTenants?: string[];
}

Usage Examples:

import { ClientAssertionCredential } from "@azure/identity";
import * as jwt from "jsonwebtoken";

// Custom assertion generation function
function createAssertion(): string {
  const payload = {
    iss: clientId,        // issuer (client ID)
    sub: clientId,        // subject (client ID)  
    aud: `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
    exp: Math.floor(Date.now() / 1000) + 600, // expires in 10 minutes
    nbf: Math.floor(Date.now() / 1000),       // not before now
    jti: generateUniqueId()                   // unique JWT ID
  };

  return jwt.sign(payload, privateKey, { algorithm: 'RS256' });
}

const credential = new ClientAssertionCredential(
  tenantId,
  clientId,
  createAssertion
);

// The getAssertion function is called each time a new token is needed
const token = await credential.getToken("https://graph.microsoft.com/.default");

Common Configuration Patterns

Multi-Tenant Service Principal

const credential = new ClientSecretCredential(
  tenantId,
  clientId, 
  clientSecret,
  {
    additionallyAllowedTenants: ["*"] // Allow access to any tenant
  }
);

// Or specify specific additional tenants
const credential = new ClientSecretCredential(
  tenantId,
  clientId,
  clientSecret, 
  {
    additionallyAllowedTenants: [
      "tenant-1-id",
      "tenant-2-id"
    ]
  }
);

Government Cloud Authentication

import { AzureAuthorityHosts } from "@azure/identity";

const credential = new ClientSecretCredential(
  tenantId,
  clientId,
  clientSecret,
  {
    authorityHost: AzureAuthorityHosts.AzureGovernment
  }
);

Certificate Chain Inclusion

// Include certificate chain in token requests for additional security
const credential = new ClientCertificateCredential(
  tenantId,
  clientId,
  certificatePath,
  {
    sendCertificateChain: true
  }
);

Environment Variable Configuration

Service principal credentials can be configured using environment variables when used with EnvironmentCredential or DefaultAzureCredential:

Client Secret:

  • AZURE_TENANT_ID - The tenant ID
  • AZURE_CLIENT_ID - The client ID
  • AZURE_CLIENT_SECRET - The client secret

Client Certificate:

  • AZURE_TENANT_ID - The tenant ID
  • AZURE_CLIENT_ID - The client ID
  • AZURE_CLIENT_CERTIFICATE_PATH - Path to certificate file
  • AZURE_CLIENT_CERTIFICATE_PASSWORD - Certificate password (optional)
  • AZURE_CLIENT_SEND_CERTIFICATE_CHAIN - Include certificate chain (optional)

Federated Identity (Client Assertion):

  • AZURE_TENANT_ID - The tenant ID
  • AZURE_CLIENT_ID - The client ID
  • AZURE_FEDERATED_TOKEN_FILE - Path to federated token file