or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

credential-providers.mdindex.mdjwt.mdrest-client.mdtwiml.mdwebhooks.md

credential-providers.mddocs/

0

# Credential Providers

1

2

Credential providers offer flexible authentication strategies for the Twilio SDK beyond basic username/password authentication. They support OAuth2 client credentials, organizational accounts, and scenarios where no authentication is required.

3

4

## Capabilities

5

6

### ClientCredentialProvider

7

8

OAuth2 client credentials provider for API authentication using client ID and secret instead of Account SID and Auth Token.

9

10

```typescript { .api }

11

/**

12

* OAuth2 client credentials provider for secure API authentication

13

* Uses client credentials grant flow for token-based authentication

14

*/

15

class ClientCredentialProvider extends CredentialProvider {

16

grantType: string;

17

clientId: string;

18

clientSecret: string;

19

tokenManager: TokenManager | null;

20

21

constructor();

22

23

/**

24

* Convert to authentication strategy for HTTP requests

25

* @returns TokenAuthStrategy with managed OAuth2 tokens

26

*/

27

toAuthStrategy(): AuthStrategy;

28

}

29

```

30

31

### ClientCredentialProviderBuilder

32

33

Builder pattern for constructing client credential providers with fluent configuration.

34

35

```typescript { .api }

36

/**

37

* Builder for ClientCredentialProvider with fluent configuration

38

* Provides step-by-step construction with validation

39

*/

40

class ClientCredentialProviderBuilder {

41

constructor();

42

43

/**

44

* Set the OAuth2 client ID

45

* @param clientId - The client identifier from Twilio console

46

* @returns Builder instance for method chaining

47

*/

48

setClientId(clientId: string): ClientCredentialProviderBuilder;

49

50

/**

51

* Set the OAuth2 client secret

52

* @param clientSecret - The client secret from Twilio console

53

* @returns Builder instance for method chaining

54

*/

55

setClientSecret(clientSecret: string): ClientCredentialProviderBuilder;

56

57

/**

58

* Set custom token manager (optional)

59

* @param tokenManager - Custom token manager implementation

60

* @returns Builder instance for method chaining

61

*/

62

setTokenManager(tokenManager: TokenManager): ClientCredentialProviderBuilder;

63

64

/**

65

* Build the configured credential provider

66

* @returns Configured ClientCredentialProvider instance

67

*/

68

build(): ClientCredentialProvider;

69

}

70

```

71

72

**Usage Examples:**

73

74

```typescript

75

import TwilioSDK from "twilio";

76

77

// Access credential provider builders

78

const { ClientCredentialProviderBuilder, Twilio } = TwilioSDK;

79

80

// Basic OAuth2 authentication

81

const credentialProvider = new ClientCredentialProviderBuilder()

82

.setClientId("your_client_id")

83

.setClientSecret("your_client_secret")

84

.build();

85

86

// Create Twilio client with OAuth2 credentials

87

const client = new Twilio();

88

client.setCredentialProvider(credentialProvider);

89

90

// Use client normally - authentication handled automatically

91

const message = await client.messages.create({

92

body: "Hello from OAuth2!",

93

from: "+1234567890",

94

to: "+0987654321"

95

});

96

97

// With custom token manager

98

const customTokenManager = new CustomTokenManager();

99

const provider = new ClientCredentialProviderBuilder()

100

.setClientId("client_id")

101

.setClientSecret("client_secret")

102

.setTokenManager(customTokenManager)

103

.build();

104

```

105

106

### OrgsCredentialProvider

107

108

Organization-level credential provider for multi-tenant applications and enterprise account management.

109

110

```typescript { .api }

111

/**

112

* Organization credential provider for enterprise and multi-tenant applications

113

* Provides organization-scoped authentication with hierarchical access control

114

*/

115

class OrgsCredentialProvider extends CredentialProvider {

116

grantType: string;

117

clientId: string;

118

clientSecret: string;

119

tokenManager: TokenManager | null;

120

121

constructor();

122

123

/**

124

* Convert to authentication strategy for HTTP requests

125

* @returns TokenAuthStrategy with organization-scoped tokens

126

*/

127

toAuthStrategy(): AuthStrategy;

128

}

129

```

130

131

### OrgsCredentialProviderBuilder

132

133

Builder for organization credential providers with enterprise-specific configuration.

134

135

```typescript { .api }

136

/**

137

* Builder for OrgsCredentialProvider with organization-specific configuration

138

* Supports enterprise account hierarchies and multi-tenant architectures

139

*/

140

class OrgsCredentialProviderBuilder {

141

constructor();

142

143

/**

144

* Set the organization client ID

145

* @param clientId - The organization client identifier

146

* @returns Builder instance for method chaining

147

*/

148

setClientId(clientId: string): OrgsCredentialProviderBuilder;

149

150

/**

151

* Set the organization client secret

152

* @param clientSecret - The organization client secret

153

* @returns Builder instance for method chaining

154

*/

155

setClientSecret(clientSecret: string): OrgsCredentialProviderBuilder;

156

157

/**

158

* Set custom organization token manager

159

* @param tokenManager - Custom token manager for org-scoped tokens

160

* @returns Builder instance for method chaining

161

*/

162

setTokenManager(tokenManager: TokenManager): OrgsCredentialProviderBuilder;

163

164

/**

165

* Build the configured organization credential provider

166

* @returns Configured OrgsCredentialProvider instance

167

*/

168

build(): OrgsCredentialProvider;

169

}

170

```

171

172

**Usage Examples:**

173

174

```typescript

175

import TwilioSDK from "twilio";

176

177

// Access organization credential provider builder

178

const { OrgsCredentialProviderBuilder, Twilio } = TwilioSDK;

179

180

// Organization-level authentication

181

const orgProvider = new OrgsCredentialProviderBuilder()

182

.setClientId("org_client_id")

183

.setClientSecret("org_client_secret")

184

.build();

185

186

// Multi-tenant application setup

187

class TenantManager {

188

private providers = new Map<string, OrgsCredentialProvider>();

189

190

createTenantProvider(tenantId: string, clientId: string, clientSecret: string) {

191

const provider = new OrgsCredentialProviderBuilder()

192

.setClientId(clientId)

193

.setClientSecret(clientSecret)

194

.build();

195

196

this.providers.set(tenantId, provider);

197

return provider;

198

}

199

200

getTwilioClient(tenantId: string): Twilio {

201

const provider = this.providers.get(tenantId);

202

if (!provider) throw new Error(`No provider for tenant ${tenantId}`);

203

204

const client = new Twilio();

205

client.setCredentialProvider(provider);

206

return client;

207

}

208

}

209

```

210

211

### NoAuthCredentialProvider

212

213

No-authentication provider for accessing public endpoints or testing scenarios where authentication is not required.

214

215

```typescript { .api }

216

/**

217

* No-authentication credential provider for public endpoints

218

* Used for accessing Twilio resources that don't require authentication

219

*/

220

class NoAuthCredentialProvider extends CredentialProvider {

221

constructor();

222

223

/**

224

* Convert to no-auth strategy that bypasses authentication

225

* @returns NoAuthStrategy that doesn't add authentication headers

226

*/

227

toAuthStrategy(): AuthStrategy;

228

}

229

```

230

231

**Usage Examples:**

232

233

```typescript

234

import TwilioSDK from "twilio";

235

236

// Access no-auth credential provider

237

const { NoAuthCredentialProvider, Twilio } = TwilioSDK;

238

239

// For public endpoints or development testing

240

const noAuthProvider = new NoAuthCredentialProvider();

241

242

const client = new Twilio();

243

client.setCredentialProvider(noAuthProvider);

244

245

// Use for public endpoints that don't require auth

246

// Note: Most Twilio APIs do require authentication

247

const publicData = await client.request({

248

method: "GET",

249

uri: "https://api.twilio.com/public-endpoint"

250

});

251

252

// Development/testing scenario

253

if (process.env.NODE_ENV === "test") {

254

const testClient = new Twilio();

255

testClient.setCredentialProvider(new NoAuthCredentialProvider());

256

// Use for mocked/stubbed testing

257

}

258

```

259

260

### Base CredentialProvider

261

262

Abstract base class for all credential providers defining the common interface.

263

264

```typescript { .api }

265

/**

266

* Abstract base class for all credential providers

267

* Defines the common interface for authentication strategies

268

*/

269

abstract class CredentialProvider {

270

private authType: string;

271

272

protected constructor(authType: string);

273

274

/**

275

* Get the authentication type identifier

276

* @returns String identifier for the auth type

277

*/

278

getAuthType(): string;

279

280

/**

281

* Convert provider to authentication strategy for HTTP requests

282

* @returns AuthStrategy implementation for this provider type

283

*/

284

abstract toAuthStrategy(): AuthStrategy;

285

}

286

```

287

288

### Authentication Strategies

289

290

The authentication strategies that credential providers generate for HTTP client usage.

291

292

```typescript { .api }

293

/**

294

* Authentication strategy interface for HTTP request authentication

295

* Applied to outgoing requests to add appropriate authentication headers

296

*/

297

interface AuthStrategy {

298

/**

299

* Apply authentication to an HTTP request

300

* @param request - The request configuration to authenticate

301

* @returns Promise resolving to authenticated request config

302

*/

303

apply(request: RequestConfig): Promise<RequestConfig>;

304

}

305

306

/**

307

* Token-based authentication strategy using OAuth2 or similar tokens

308

* Automatically handles token refresh and management

309

*/

310

class TokenAuthStrategy implements AuthStrategy {

311

constructor(tokenManager: TokenManager);

312

apply(request: RequestConfig): Promise<RequestConfig>;

313

}

314

315

/**

316

* No-authentication strategy that bypasses authentication

317

* Leaves requests unmodified without adding auth headers

318

*/

319

class NoAuthStrategy implements AuthStrategy {

320

apply(request: RequestConfig): Promise<RequestConfig>;

321

}

322

```

323

324

### Token Management

325

326

Token managers handle the lifecycle of OAuth2 and other authentication tokens.

327

328

```typescript { .api }

329

/**

330

* Token manager interface for OAuth2 and bearer token lifecycle management

331

* Handles token acquisition, refresh, and caching

332

*/

333

interface TokenManager {

334

/**

335

* Get a valid access token, refreshing if necessary

336

* @returns Promise resolving to current valid access token

337

*/

338

getToken(): Promise<string>;

339

340

/**

341

* Force refresh of the current token

342

* @returns Promise resolving to new access token

343

*/

344

refreshToken(): Promise<string>;

345

346

/**

347

* Clear cached tokens and force re-authentication

348

*/

349

clearToken(): void;

350

}

351

352

/**

353

* API token manager for standard Twilio API OAuth2 flows

354

* Handles client credentials grant type with automatic refresh

355

*/

356

class ApiTokenManager implements TokenManager {

357

constructor(options: TokenManagerOptions);

358

getToken(): Promise<string>;

359

refreshToken(): Promise<string>;

360

clearToken(): void;

361

}

362

363

/**

364

* Organization token manager for enterprise OAuth2 flows

365

* Provides organization-scoped tokens with hierarchical access

366

*/

367

class OrgsTokenManager implements TokenManager {

368

constructor(options: TokenManagerOptions);

369

getToken(): Promise<string>;

370

refreshToken(): Promise<string>;

371

clearToken(): void;

372

}

373

374

interface TokenManagerOptions {

375

/** OAuth2 grant type (typically "client_credentials") */

376

grantType: string;

377

/** OAuth2 client identifier */

378

clientId: string;

379

/** OAuth2 client secret */

380

clientSecret: string;

381

/** Token endpoint URL (optional, uses Twilio default) */

382

tokenUrl?: string;

383

/** Token cache TTL in seconds (optional) */

384

cacheTtl?: number;

385

}

386

```

387

388

**Usage Examples:**

389

390

```typescript

391

// Custom token manager implementation

392

class CustomTokenManager implements TokenManager {

393

private token: string | null = null;

394

private expiry: Date | null = null;

395

396

async getToken(): Promise<string> {

397

if (!this.token || !this.expiry || this.expiry <= new Date()) {

398

return this.refreshToken();

399

}

400

return this.token;

401

}

402

403

async refreshToken(): Promise<string> {

404

// Custom token acquisition logic

405

const response = await fetch("https://your-auth-server.com/token", {

406

method: "POST",

407

headers: { "Content-Type": "application/json" },

408

body: JSON.stringify({

409

grant_type: "client_credentials",

410

client_id: this.clientId,

411

client_secret: this.clientSecret

412

})

413

});

414

415

const data = await response.json();

416

this.token = data.access_token;

417

this.expiry = new Date(Date.now() + (data.expires_in * 1000));

418

419

return this.token;

420

}

421

422

clearToken(): void {

423

this.token = null;

424

this.expiry = null;

425

}

426

}

427

```

428

429

## Types

430

431

```typescript { .api }

432

interface RequestConfig {

433

method: string;

434

url: string;

435

headers: Record<string, string>;

436

data?: any;

437

timeout?: number;

438

}

439

440

type AuthType = "client-credentials" | "noauth" | "basic";

441

442

interface ProviderConfig {

443

authType: AuthType;

444

clientId?: string;

445

clientSecret?: string;

446

tokenManager?: TokenManager;

447

}

448

```