Twilio API client and TwiML generator for comprehensive telecommunications services
Token-based authentication system for client-side applications and access control. Includes access tokens, capability tokens, and various grant types for different Twilio services.
Generate JWT access tokens for client-side SDK authentication with service-specific grants.
class AccessToken:
"""JWT access token for client SDK authentication"""
def __init__(
self,
account_sid: str,
signing_key_sid: str,
secret: str,
ttl: int = 3600,
identity: str = None,
nbf: int = None
):
"""
Initialize access token.
Args:
account_sid (str): Twilio Account SID
signing_key_sid (str): API Key SID
secret (str): API Key Secret
ttl (int): Token lifetime in seconds (default: 3600)
identity (str): User identity for the token
nbf (int): Not-before timestamp
"""
def add_grant(self, grant: 'AccessTokenGrant') -> 'AccessToken':
"""
Add service grant to token.
Args:
grant (AccessTokenGrant): Service-specific grant
Returns:
AccessToken: Self for chaining
"""
def to_jwt(self) -> str:
"""
Generate JWT token string.
Returns:
str: Signed JWT token
"""
class AccessTokenGrant:
"""Base class for service grants"""
def to_payload(self) -> dict:
"""Convert grant to JWT payload dict"""Service-specific grants for different Twilio products.
class VideoGrant(AccessTokenGrant):
"""Video service access grant"""
def __init__(self, room: str = None):
"""
Args:
room (str): Video room name or SID
"""
self.room = room
class ChatGrant(AccessTokenGrant):
"""Chat/Conversations service access grant"""
def __init__(
self,
service_sid: str = None,
endpoint_id: str = None,
deployment_role_sid: str = None,
push_credential_sid: str = None
):
"""
Args:
service_sid (str): Chat service SID
endpoint_id (str): Unique endpoint identifier
deployment_role_sid (str): Deployment role SID
push_credential_sid (str): Push notification credential SID
"""
class VoiceGrant(AccessTokenGrant):
"""Voice service access grant"""
def __init__(
self,
outgoing_application_sid: str = None,
incoming_allow: bool = None,
push_credential_sid: str = None
):
"""
Args:
outgoing_application_sid (str): TwiML app for outgoing calls
incoming_allow (bool): Allow incoming calls
push_credential_sid (str): Push notification credential SID
"""
class SyncGrant(AccessTokenGrant):
"""Sync service access grant"""
def __init__(
self,
service_sid: str = None,
endpoint_id: str = None
):
"""
Args:
service_sid (str): Sync service SID
endpoint_id (str): Unique endpoint identifier
"""
class TaskRouterGrant(AccessTokenGrant):
"""TaskRouter service access grant"""
def __init__(
self,
workspace_sid: str = None,
worker_sid: str = None,
role: str = None
):
"""
Args:
workspace_sid (str): TaskRouter workspace SID
worker_sid (str): Worker SID
role (str): Worker role
"""
class PlaybackGrant(AccessTokenGrant):
"""Media playback access grant"""
def __init__(self, grant: dict = None):
"""
Args:
grant (dict): Playback grant configuration
"""Access token examples:
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import (
VideoGrant, ChatGrant, VoiceGrant, SyncGrant
)
# Basic video token
token = AccessToken(
account_sid='ACxxxxx',
signing_key_sid='SKxxxxx',
secret='your_api_secret',
identity='user123'
)
token.add_grant(VideoGrant(room='my-room'))
jwt_token = token.to_jwt()
# Chat token with multiple grants
token = AccessToken('ACxxxxx', 'SKxxxxx', 'secret', identity='alice')
token.add_grant(ChatGrant(
service_sid='ISxxxxx',
endpoint_id='alice-mobile'
))
token.add_grant(VoiceGrant(
outgoing_application_sid='APxxxxx',
incoming_allow=True
))
jwt = token.to_jwt()
# Sync token for real-time data
token = AccessToken('ACxxxxx', 'SKxxxxx', 'secret', identity='user456')
token.add_grant(SyncGrant(
service_sid='ISxxxxx',
endpoint_id='user456-web'
))
sync_token = token.to_jwt()Legacy capability tokens for Twilio Client SDK authentication.
class ClientCapabilityToken:
"""Legacy client capability token"""
def __init__(self, account_sid: str, auth_token: str):
"""
Args:
account_sid (str): Twilio Account SID
auth_token (str): Account Auth Token
"""
def allow_client_incoming(self, client_name: str) -> 'ClientCapabilityToken':
"""
Allow incoming connections to client.
Args:
client_name (str): Client identifier
Returns:
ClientCapabilityToken: Self for chaining
"""
def allow_client_outgoing(
self,
application_sid: str,
**params
) -> 'ClientCapabilityToken':
"""
Allow outgoing calls from client.
Args:
application_sid (str): TwiML application SID
**params: Additional parameters for outgoing calls
Returns:
ClientCapabilityToken: Self for chaining
"""
def allow_event_stream(self, **filters) -> 'ClientCapabilityToken':
"""
Allow event stream access.
Args:
**filters: Event filtering parameters
Returns:
ClientCapabilityToken: Self for chaining
"""
def generate(self, ttl: int = 3600) -> str:
"""
Generate capability token.
Args:
ttl (int): Token lifetime in seconds
Returns:
str: Capability token string
"""Capability tokens for TaskRouter worker authentication.
class TaskRouterCapabilityToken:
"""TaskRouter capability token"""
def __init__(
self,
account_sid: str,
auth_token: str,
workspace_sid: str,
channel_id: str,
ttl: int = 3600
):
"""
Args:
account_sid (str): Account SID
auth_token (str): Auth token
workspace_sid (str): TaskRouter workspace SID
channel_id (str): Worker channel ID
ttl (int): Token lifetime in seconds
"""
def allow_fetch_subresources(self) -> 'TaskRouterCapabilityToken':
"""Allow fetching subresources"""
def allow_updates_subresources(self) -> 'TaskRouterCapabilityToken':
"""Allow updating subresources"""
def allow_delete_subresources(self) -> 'TaskRouterCapabilityToken':
"""Allow deleting subresources"""
def generate(self) -> str:
"""
Generate capability token.
Returns:
str: Capability token string
"""Utilities for JWT token handling and validation.
class Jwt:
"""Base JWT functionality"""
def __init__(
self,
secret_key: str,
issuer: str = None,
subject: str = None,
algorithm: str = 'HS256',
ttl: int = 3600,
valid_until: int = None
):
"""
Args:
secret_key (str): Signing secret
issuer (str): Token issuer
subject (str): Token subject
algorithm (str): Signing algorithm
ttl (int): Time to live in seconds
valid_until (int): Expiration timestamp
"""
def encode(self, payload: dict) -> str:
"""
Encode payload as JWT.
Args:
payload (dict): JWT payload
Returns:
str: Encoded JWT token
"""
@staticmethod
def decode(token: str, secret: str) -> dict:
"""
Decode JWT token.
Args:
token (str): JWT token string
secret (str): Verification secret
Returns:
dict: Decoded payload
Raises:
JwtDecodeError: If token is invalid
"""
class JwtDecodeError(Exception):
"""JWT decoding error exception"""JWT examples:
from twilio.jwt.client import ClientCapabilityToken
from twilio.jwt.taskrouter import TaskRouterCapabilityToken
# Client capability token
capability = ClientCapabilityToken('ACxxxxx', 'auth_token')
capability.allow_client_incoming('alice')
capability.allow_client_outgoing('APxxxxx', ClientName='alice')
token = capability.generate(ttl=7200)
# TaskRouter worker token
taskrouter_token = TaskRouterCapabilityToken(
account_sid='ACxxxxx',
auth_token='auth_token',
workspace_sid='WSxxxxx',
channel_id='alice'
)
taskrouter_token.allow_fetch_subresources()
taskrouter_token.allow_updates_subresources()
worker_token = taskrouter_token.generate()Install with Tessl CLI
npx tessl i tessl/pypi-twilio