0
# Authentication & JWT
1
2
Token-based authentication system for client-side applications and access control. Includes access tokens, capability tokens, and various grant types for different Twilio services.
3
4
## Capabilities
5
6
### Access Tokens
7
8
Generate JWT access tokens for client-side SDK authentication with service-specific grants.
9
10
```python { .api }
11
class AccessToken:
12
"""JWT access token for client SDK authentication"""
13
14
def __init__(
15
self,
16
account_sid: str,
17
signing_key_sid: str,
18
secret: str,
19
ttl: int = 3600,
20
identity: str = None,
21
nbf: int = None
22
):
23
"""
24
Initialize access token.
25
26
Args:
27
account_sid (str): Twilio Account SID
28
signing_key_sid (str): API Key SID
29
secret (str): API Key Secret
30
ttl (int): Token lifetime in seconds (default: 3600)
31
identity (str): User identity for the token
32
nbf (int): Not-before timestamp
33
"""
34
35
def add_grant(self, grant: 'AccessTokenGrant') -> 'AccessToken':
36
"""
37
Add service grant to token.
38
39
Args:
40
grant (AccessTokenGrant): Service-specific grant
41
42
Returns:
43
AccessToken: Self for chaining
44
"""
45
46
def to_jwt(self) -> str:
47
"""
48
Generate JWT token string.
49
50
Returns:
51
str: Signed JWT token
52
"""
53
54
class AccessTokenGrant:
55
"""Base class for service grants"""
56
57
def to_payload(self) -> dict:
58
"""Convert grant to JWT payload dict"""
59
```
60
61
### Grant Types
62
63
Service-specific grants for different Twilio products.
64
65
```python { .api }
66
class VideoGrant(AccessTokenGrant):
67
"""Video service access grant"""
68
69
def __init__(self, room: str = None):
70
"""
71
Args:
72
room (str): Video room name or SID
73
"""
74
self.room = room
75
76
class ChatGrant(AccessTokenGrant):
77
"""Chat/Conversations service access grant"""
78
79
def __init__(
80
self,
81
service_sid: str = None,
82
endpoint_id: str = None,
83
deployment_role_sid: str = None,
84
push_credential_sid: str = None
85
):
86
"""
87
Args:
88
service_sid (str): Chat service SID
89
endpoint_id (str): Unique endpoint identifier
90
deployment_role_sid (str): Deployment role SID
91
push_credential_sid (str): Push notification credential SID
92
"""
93
94
class VoiceGrant(AccessTokenGrant):
95
"""Voice service access grant"""
96
97
def __init__(
98
self,
99
outgoing_application_sid: str = None,
100
incoming_allow: bool = None,
101
push_credential_sid: str = None
102
):
103
"""
104
Args:
105
outgoing_application_sid (str): TwiML app for outgoing calls
106
incoming_allow (bool): Allow incoming calls
107
push_credential_sid (str): Push notification credential SID
108
"""
109
110
class SyncGrant(AccessTokenGrant):
111
"""Sync service access grant"""
112
113
def __init__(
114
self,
115
service_sid: str = None,
116
endpoint_id: str = None
117
):
118
"""
119
Args:
120
service_sid (str): Sync service SID
121
endpoint_id (str): Unique endpoint identifier
122
"""
123
124
class TaskRouterGrant(AccessTokenGrant):
125
"""TaskRouter service access grant"""
126
127
def __init__(
128
self,
129
workspace_sid: str = None,
130
worker_sid: str = None,
131
role: str = None
132
):
133
"""
134
Args:
135
workspace_sid (str): TaskRouter workspace SID
136
worker_sid (str): Worker SID
137
role (str): Worker role
138
"""
139
140
class PlaybackGrant(AccessTokenGrant):
141
"""Media playback access grant"""
142
143
def __init__(self, grant: dict = None):
144
"""
145
Args:
146
grant (dict): Playback grant configuration
147
"""
148
```
149
150
Access token examples:
151
152
```python
153
from twilio.jwt.access_token import AccessToken
154
from twilio.jwt.access_token.grants import (
155
VideoGrant, ChatGrant, VoiceGrant, SyncGrant
156
)
157
158
# Basic video token
159
token = AccessToken(
160
account_sid='ACxxxxx',
161
signing_key_sid='SKxxxxx',
162
secret='your_api_secret',
163
identity='user123'
164
)
165
token.add_grant(VideoGrant(room='my-room'))
166
jwt_token = token.to_jwt()
167
168
# Chat token with multiple grants
169
token = AccessToken('ACxxxxx', 'SKxxxxx', 'secret', identity='alice')
170
token.add_grant(ChatGrant(
171
service_sid='ISxxxxx',
172
endpoint_id='alice-mobile'
173
))
174
token.add_grant(VoiceGrant(
175
outgoing_application_sid='APxxxxx',
176
incoming_allow=True
177
))
178
jwt = token.to_jwt()
179
180
# Sync token for real-time data
181
token = AccessToken('ACxxxxx', 'SKxxxxx', 'secret', identity='user456')
182
token.add_grant(SyncGrant(
183
service_sid='ISxxxxx',
184
endpoint_id='user456-web'
185
))
186
sync_token = token.to_jwt()
187
```
188
189
### Client Capability Tokens
190
191
Legacy capability tokens for Twilio Client SDK authentication.
192
193
```python { .api }
194
class ClientCapabilityToken:
195
"""Legacy client capability token"""
196
197
def __init__(self, account_sid: str, auth_token: str):
198
"""
199
Args:
200
account_sid (str): Twilio Account SID
201
auth_token (str): Account Auth Token
202
"""
203
204
def allow_client_incoming(self, client_name: str) -> 'ClientCapabilityToken':
205
"""
206
Allow incoming connections to client.
207
208
Args:
209
client_name (str): Client identifier
210
211
Returns:
212
ClientCapabilityToken: Self for chaining
213
"""
214
215
def allow_client_outgoing(
216
self,
217
application_sid: str,
218
**params
219
) -> 'ClientCapabilityToken':
220
"""
221
Allow outgoing calls from client.
222
223
Args:
224
application_sid (str): TwiML application SID
225
**params: Additional parameters for outgoing calls
226
227
Returns:
228
ClientCapabilityToken: Self for chaining
229
"""
230
231
def allow_event_stream(self, **filters) -> 'ClientCapabilityToken':
232
"""
233
Allow event stream access.
234
235
Args:
236
**filters: Event filtering parameters
237
238
Returns:
239
ClientCapabilityToken: Self for chaining
240
"""
241
242
def generate(self, ttl: int = 3600) -> str:
243
"""
244
Generate capability token.
245
246
Args:
247
ttl (int): Token lifetime in seconds
248
249
Returns:
250
str: Capability token string
251
"""
252
```
253
254
### TaskRouter Capability Tokens
255
256
Capability tokens for TaskRouter worker authentication.
257
258
```python { .api }
259
class TaskRouterCapabilityToken:
260
"""TaskRouter capability token"""
261
262
def __init__(
263
self,
264
account_sid: str,
265
auth_token: str,
266
workspace_sid: str,
267
channel_id: str,
268
ttl: int = 3600
269
):
270
"""
271
Args:
272
account_sid (str): Account SID
273
auth_token (str): Auth token
274
workspace_sid (str): TaskRouter workspace SID
275
channel_id (str): Worker channel ID
276
ttl (int): Token lifetime in seconds
277
"""
278
279
def allow_fetch_subresources(self) -> 'TaskRouterCapabilityToken':
280
"""Allow fetching subresources"""
281
282
def allow_updates_subresources(self) -> 'TaskRouterCapabilityToken':
283
"""Allow updating subresources"""
284
285
def allow_delete_subresources(self) -> 'TaskRouterCapabilityToken':
286
"""Allow deleting subresources"""
287
288
def generate(self) -> str:
289
"""
290
Generate capability token.
291
292
Returns:
293
str: Capability token string
294
"""
295
```
296
297
### JWT Utilities
298
299
Utilities for JWT token handling and validation.
300
301
```python { .api }
302
class Jwt:
303
"""Base JWT functionality"""
304
305
def __init__(
306
self,
307
secret_key: str,
308
issuer: str = None,
309
subject: str = None,
310
algorithm: str = 'HS256',
311
ttl: int = 3600,
312
valid_until: int = None
313
):
314
"""
315
Args:
316
secret_key (str): Signing secret
317
issuer (str): Token issuer
318
subject (str): Token subject
319
algorithm (str): Signing algorithm
320
ttl (int): Time to live in seconds
321
valid_until (int): Expiration timestamp
322
"""
323
324
def encode(self, payload: dict) -> str:
325
"""
326
Encode payload as JWT.
327
328
Args:
329
payload (dict): JWT payload
330
331
Returns:
332
str: Encoded JWT token
333
"""
334
335
@staticmethod
336
def decode(token: str, secret: str) -> dict:
337
"""
338
Decode JWT token.
339
340
Args:
341
token (str): JWT token string
342
secret (str): Verification secret
343
344
Returns:
345
dict: Decoded payload
346
347
Raises:
348
JwtDecodeError: If token is invalid
349
"""
350
351
class JwtDecodeError(Exception):
352
"""JWT decoding error exception"""
353
```
354
355
JWT examples:
356
357
```python
358
from twilio.jwt.client import ClientCapabilityToken
359
from twilio.jwt.taskrouter import TaskRouterCapabilityToken
360
361
# Client capability token
362
capability = ClientCapabilityToken('ACxxxxx', 'auth_token')
363
capability.allow_client_incoming('alice')
364
capability.allow_client_outgoing('APxxxxx', ClientName='alice')
365
token = capability.generate(ttl=7200)
366
367
# TaskRouter worker token
368
taskrouter_token = TaskRouterCapabilityToken(
369
account_sid='ACxxxxx',
370
auth_token='auth_token',
371
workspace_sid='WSxxxxx',
372
channel_id='alice'
373
)
374
taskrouter_token.allow_fetch_subresources()
375
taskrouter_token.allow_updates_subresources()
376
worker_token = taskrouter_token.generate()
377
```