or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

jwt.mddocs/

0

# JWT Authentication

1

2

JWT (JSON Web Token) authentication utilities provide secure token generation and validation for Twilio client applications, TaskRouter workers, and service capabilities. These tokens enable secure client-side access to Twilio services without exposing credentials.

3

4

## Capabilities

5

6

### AccessToken

7

8

Generates JWT access tokens for client-side applications that need to connect to Twilio services like Voice, Video, Chat, and Sync.

9

10

```typescript { .api }

11

/**

12

* JWT access token generator for Twilio client applications

13

* Used to authenticate client-side applications and grant specific service capabilities

14

*/

15

class AccessToken {

16

/** Default signing algorithm */

17

static DEFAULT_ALGORITHM: "HS256";

18

/** Supported signing algorithms */

19

static ALGORITHMS: ["HS256", "HS384", "HS512"];

20

21

accountSid: string;

22

keySid: string;

23

secret: string;

24

ttl: number;

25

identity: string;

26

nbf?: number;

27

region?: string;

28

grants: Grant<any, any, any>[];

29

30

/**

31

* Creates a new access token instance

32

* @param accountSid - The account's unique ID to which access is scoped

33

* @param keySid - The signing key's unique ID (API Key SID)

34

* @param secret - The secret to sign the token with (API Key Secret)

35

* @param options - Token configuration options

36

*/

37

constructor(

38

accountSid: string,

39

keySid: string,

40

secret: string,

41

options: AccessTokenOptions

42

);

43

44

/**

45

* Add a service grant to the token

46

* @param grant - Service-specific grant (Voice, Video, Chat, etc.)

47

*/

48

addGrant<T extends Grant<any, any, any>>(grant: T): void;

49

50

/**

51

* Generate the JWT token string

52

* @param algorithm - Signing algorithm (default: HS256)

53

* @returns JWT token string

54

*/

55

toJwt(algorithm?: "HS256" | "HS384" | "HS512"): string;

56

}

57

58

interface AccessTokenOptions {

59

/** Time to live in seconds (default: 3600) */

60

ttl?: number;

61

/** Identity of the client user (required) */

62

identity: string;

63

/** Not before time from epoch in seconds */

64

nbf?: number;

65

/** Region value associated with this account */

66

region?: string;

67

}

68

```

69

70

**Usage Examples:**

71

72

```typescript

73

import TwilioSDK from "twilio";

74

75

// Access JWT utilities via namespace

76

const { jwt } = TwilioSDK;

77

78

// Create access token for voice calling

79

const accessToken = new jwt.AccessToken(

80

"AC123...", // Account SID

81

"SK456...", // API Key SID

82

"secret", // API Key Secret

83

{ identity: "alice", ttl: 3600 }

84

);

85

86

// Add voice grant for incoming and outgoing calls

87

const voiceGrant = new jwt.AccessToken.VoiceGrant({

88

incomingAllow: true,

89

outgoingApplicationSid: "AP789..."

90

});

91

accessToken.addGrant(voiceGrant);

92

93

// Generate token for client application

94

const token = accessToken.toJwt();

95

```

96

97

### Service Grants

98

99

Grant classes for specific Twilio services that can be added to access tokens.

100

101

```typescript { .api }

102

abstract class Grant<TOptions, TPayload, TKey> {

103

key: TKey;

104

105

protected constructor(key: TKey);

106

abstract toPayload(): TPayload;

107

}

108

109

/** TaskRouter grant for worker and workspace access */

110

class TaskRouterGrant extends Grant<TaskRouterGrantOptions, TaskRouterGrantPayload, "task_router"> {

111

constructor(options?: TaskRouterGrantOptions);

112

}

113

114

interface TaskRouterGrantOptions {

115

/** Workspace SID for TaskRouter operations */

116

workspaceSid?: string;

117

/** Worker SID for specific worker access */

118

workerSid?: string;

119

/** Role for the worker (e.g., "worker", "supervisor") */

120

role?: string;

121

}

122

123

/** Chat grant for messaging and conversations */

124

class ChatGrant extends Grant<ChatGrantOptions, ChatGrantPayload, "chat"> {

125

constructor(options?: ChatGrantOptions);

126

}

127

128

interface ChatGrantOptions {

129

/** Chat service SID */

130

serviceSid?: string;

131

/** Endpoint ID for the client */

132

endpointId?: string;

133

/** Deployment role SID */

134

deploymentRoleSid?: string;

135

/** Push credential SID for notifications */

136

pushCredentialSid?: string;

137

}

138

139

/** Video grant for room access and recording */

140

class VideoGrant extends Grant<VideoGrantOptions, VideoGrantPayload, "video"> {

141

constructor(options?: VideoGrantOptions);

142

}

143

144

interface VideoGrantOptions {

145

/** Specific room name to join */

146

room?: string;

147

}

148

149

/** Sync grant for real-time data synchronization */

150

class SyncGrant extends Grant<SyncGrantOptions, SyncGrantPayload, "data_sync"> {

151

constructor(options?: SyncGrantOptions);

152

}

153

154

interface SyncGrantOptions {

155

/** Sync service SID */

156

serviceSid?: string;

157

/** Endpoint ID for sync operations */

158

endpointId?: string;

159

}

160

161

/** Voice grant for telephony capabilities */

162

class VoiceGrant extends Grant<VoiceGrantOptions, VoiceGrantPayload, "voice"> {

163

constructor(options?: VoiceGrantOptions);

164

}

165

166

interface VoiceGrantOptions {

167

/** Allow incoming calls */

168

incomingAllow?: boolean;

169

/** Application SID for outgoing calls */

170

outgoingApplicationSid?: string;

171

/** Parameters for outgoing application */

172

outgoingApplicationParams?: object;

173

/** Endpoint ID for push notifications */

174

endpointId?: string;

175

}

176

177

/** Playback grant for media playback */

178

class PlaybackGrant extends Grant<PlaybackGrantOptions, PlaybackGrantPayload, "player"> {

179

constructor(options?: PlaybackGrantOptions);

180

}

181

182

interface PlaybackGrantOptions {

183

/** Grant access for media playback */

184

grant?: object;

185

}

186

```

187

188

**Usage Examples:**

189

190

```typescript

191

// Multi-service access token

192

const accessToken = new jwt.AccessToken("AC123...", "SK456...", "secret", {

193

identity: "user123",

194

ttl: 7200 // 2 hours

195

});

196

197

// Add multiple grants for different services

198

accessToken.addGrant(new jwt.AccessToken.VoiceGrant({

199

incomingAllow: true,

200

outgoingApplicationSid: "AP789..."

201

}));

202

203

accessToken.addGrant(new jwt.AccessToken.VideoGrant({

204

room: "support-room"

205

}));

206

207

accessToken.addGrant(new jwt.AccessToken.ChatGrant({

208

serviceSid: "IS456...",

209

endpointId: "user123"

210

}));

211

212

const token = accessToken.toJwt();

213

```

214

215

### ClientCapability

216

217

Generates JWT capability tokens for Twilio Client applications to control voice calling permissions and event access.

218

219

```typescript { .api }

220

/**

221

* JWT capability token generator for Twilio Client applications

222

* Controls permissions for voice calling and event streaming

223

*/

224

class ClientCapability {

225

static EventStreamScope: typeof EventStreamScope;

226

static IncomingClientScope: typeof IncomingClientScope;

227

static OutgoingClientScope: typeof OutgoingClientScope;

228

229

accountSid: string;

230

authToken: string;

231

ttl: number;

232

scopes: Scope[];

233

234

/**

235

* Creates a new client capability instance

236

* @param options - Capability configuration

237

*/

238

constructor(options: ClientCapabilityOptions);

239

240

/**

241

* Add a capability scope to the token

242

* @param scope - Capability scope (incoming, outgoing, or event stream)

243

*/

244

addScope(scope: Scope): void;

245

246

/**

247

* Generate the capability token

248

* @returns JWT capability token string

249

*/

250

toJwt(): string;

251

}

252

253

interface ClientCapabilityOptions {

254

/** Twilio Account SID */

255

accountSid: string;

256

/** Auth Token for signing */

257

authToken: string;

258

/** Time to live in seconds (default: 3600) */

259

ttl?: number;

260

}

261

```

262

263

### Capability Scopes

264

265

Scope classes that define specific permissions for Twilio Client applications.

266

267

```typescript { .api }

268

interface Scope {

269

scope: string;

270

payload(): string;

271

}

272

273

/** Allow client to receive incoming calls */

274

class IncomingClientScope implements Scope {

275

scope: "scope:client:incoming";

276

clientName: string;

277

278

constructor(clientName: string);

279

payload(): string;

280

}

281

282

/** Allow client to make outgoing calls */

283

class OutgoingClientScope implements Scope {

284

scope: "scope:client:outgoing";

285

applicationSid: string;

286

clientName?: string;

287

params?: object;

288

289

constructor(options: OutgoingClientScopeOptions);

290

payload(): string;

291

}

292

293

interface OutgoingClientScopeOptions {

294

/** TwiML Application SID for outgoing calls */

295

applicationSid: string;

296

/** Client name for identification */

297

clientName?: string;

298

/** Additional parameters for the application */

299

params?: object;

300

}

301

302

/** Allow client to subscribe to event streams */

303

class EventStreamScope implements Scope {

304

scope: "scope:stream:subscribe";

305

filters: object;

306

307

constructor(filters?: object);

308

payload(): string;

309

}

310

```

311

312

**Usage Examples:**

313

314

```typescript

315

// Client capability for voice calling

316

const capability = new jwt.ClientCapability({

317

accountSid: "AC123...",

318

authToken: "auth_token_here",

319

ttl: 3600

320

});

321

322

// Allow incoming calls for specific client

323

capability.addScope(new jwt.ClientCapability.IncomingClientScope("alice"));

324

325

// Allow outgoing calls through TwiML application

326

capability.addScope(new jwt.ClientCapability.OutgoingClientScope({

327

applicationSid: "AP456...",

328

clientName: "alice"

329

}));

330

331

// Allow event stream subscription with filters

332

capability.addScope(new jwt.ClientCapability.EventStreamScope({

333

account_sid: "AC123..."

334

}));

335

336

const token = capability.toJwt();

337

```

338

339

### TaskRouterCapability

340

341

Specialized JWT generator for TaskRouter workers and supervisors with workspace-level permissions.

342

343

```typescript { .api }

344

/**

345

* JWT capability generator for TaskRouter operations

346

* Provides workspace and worker-level access control

347

*/

348

class TaskRouterCapability {

349

constructor(accountSid: string, authToken: string, workspaceSid: string, channelId: string);

350

351

/**

352

* Allow worker to receive reservations

353

*/

354

allowWorkerActivityUpdates(): TaskRouterCapability;

355

356

/**

357

* Allow worker to fetch reservations

358

*/

359

allowWorkerFetchReservations(): TaskRouterCapability;

360

361

/**

362

* Allow worker to update reservations

363

*/

364

allowWorkerReservationsUpdate(): TaskRouterCapability;

365

366

/**

367

* Generate the capability token

368

*/

369

toJwt(): string;

370

}

371

```

372

373

### ValidationToken

374

375

JWT validation for incoming Twilio requests to ensure they originate from Twilio servers.

376

377

```typescript { .api }

378

/**

379

* JWT validator for incoming Twilio requests

380

* Ensures request authenticity using public key cryptography

381

*/

382

class ValidationToken {

383

static readonly DEFAULT_ALGORITHM: "RS256";

384

static readonly ALGORITHMS: ["RS256", "PS256"];

385

386

readonly accountSid: string;

387

readonly credentialSid: string;

388

readonly signingKey: string;

389

readonly privateKey: string;

390

readonly algorithm: Algorithm;

391

ttl: number;

392

393

/**

394

* Creates a validation token instance

395

* @param opts - Validation configuration options

396

*/

397

constructor(opts: ValidationTokenOptions);

398

399

/**

400

* Get request canonicalizer for signature validation

401

* @param request - HTTP request object

402

* @returns Request canonicalizer instance

403

*/

404

getRequestCanonicalizer(request: ValidationRequest): RequestCanonicalizer;

405

406

/**

407

* Generate validation token for outbound requests

408

* @param canonicalizer - Request canonicalizer

409

* @returns JWT validation token

410

*/

411

generateToken(canonicalizer: RequestCanonicalizer): string;

412

}

413

414

interface ValidationTokenOptions {

415

/** Account SID */

416

accountSid: string;

417

/** Public key credential SID */

418

credentialSid: string;

419

/** Signing key identifier */

420

signingKey: string;

421

/** Private key for signing */

422

privateKey: string;

423

/** Signing algorithm (default: RS256) */

424

algorithm?: "RS256" | "PS256";

425

/** Token time to live (default: 300) */

426

ttl?: number;

427

}

428

429

interface ValidationRequest {

430

/** Request headers */

431

headers?: object;

432

/** Request URL */

433

url: string;

434

/** HTTP method */

435

method: string;

436

/** Query parameters */

437

params?: object;

438

/** Request body data */

439

data?: any;

440

}

441

```

442

443

**Usage Examples:**

444

445

```typescript

446

// Validate incoming request from Twilio

447

const validationToken = new jwt.ValidationToken({

448

accountSid: "AC123...",

449

credentialSid: "CR456...",

450

signingKey: "signing_key_here",

451

privateKey: "-----BEGIN PRIVATE KEY-----\n...",

452

algorithm: "RS256"

453

});

454

455

// Canonicalize the request for validation

456

const canonicalizer = validationToken.getRequestCanonicalizer({

457

url: "https://myapp.com/webhook",

458

method: "POST",

459

headers: request.headers,

460

data: request.body

461

});

462

463

// Generate validation token

464

const token = validationToken.generateToken(canonicalizer);

465

```

466

467

### TaskRouter Utilities

468

469

Utility functions for TaskRouter JWT token operations and capability management.

470

471

```typescript { .api }

472

namespace util {

473

/**

474

* Build TaskRouter capability URL for specific operations

475

* @param accountSid - Account SID

476

* @param workspaceSid - Workspace SID

477

* @param channelId - Channel identifier

478

* @param version - API version (default: "v1")

479

* @returns Formatted capability URL

480

*/

481

function buildWorkspaceUrl(

482

accountSid: string,

483

workspaceSid: string,

484

channelId: string,

485

version?: string

486

): string;

487

}

488

```

489

490

## Types

491

492

```typescript { .api }

493

type Algorithm = "HS256" | "HS384" | "HS512" | "RS256" | "PS256";

494

495

interface RequestCanonicalizer {

496

/** Canonicalized request string for signature validation */

497

canonicalizedRequest: string;

498

499

/** Generate signature hash */

500

getSignatureHash(): string;

501

}

502

```