Skip to content

JWT Tokens

Tom edited this page Jul 10, 2017 · 9 revisions

[Twilio Client Capability Tokens][tokens] are required for setting up a device to send and receive calls via Twilio Client.

Setup Work

require 'twilio-ruby'

# put your own account credentials here:
account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'

# set up
capability = Twilio::JWT::ClientCapability.new account_sid, auth_token

Allow Incoming Calls

# Allow incoming calls, and give the client a name.
incomingScope = Twilio::JWT::ClientCapability::IncomingClientScope.new 'john'
capability.add_scope(incomingScope)

# Generate the token string
@token = capability.to_s

Allow Outgoing Calls

# Allow outgoing calls to an application.
outgoingScope = Twilio::JWT::ClientCapability::OutgoingClientScope.new 'AP11111111111111111111111111111111', 'john'
capability.add_scope(outgoingScope)

# Generate the token string
@token = capability.to_s

Allow Outgoing Calls With Parameters

You can send parameters to your Application's VoiceUrl by passing a hash in the initialization. Here we pass along a hypothetical user id.

params = {'user_id' => @user.id}

# Allow outgoing calls to an application and pass the user id to your server.
outgoingScope = Twilio::JWT::ClientCapability::OutgoingClientScope.new 'AP11111111111111111111111111111111', 'john', params
capability.add_scope(outgoingScope)

# Generate the token string
@token = capability.to_s 

The user_id parameter and its value will be sent to your Application's VoiceUrl along with the other parameters that Twilio usually sends, like From, To and CallSid.

Allow Multiple Capabilities

You can generate a Capability Token that supports multiple capabilities, so that your Twilio Client device can make and receive calls.

# Allow incoming calls, and give the client a name.
client_name = 'john'

# Allow incoming calls, and give the client a name.
incomingScope = Twilio::JWT::ClientCapability::IncomingClientScope.new client_name
capability.add_scope(incomingScope)

# Allow outgoing calls to an application and pass the user id to your server.
params = {'user_id' => @user.id}
outgoingScope = Twilio::JWT::ClientCapability::OutgoingClientScope.new 'AP11111111111111111111111111111111', client_name, params
capability.add_scope(outgoingScope)

# Generate the token string
@token = capability.to_s 

###Change the TTL of the Token By default all tokens generated with the Twilio helper libraries expire after one hour (3600s). But you should configure this expiration to be as short as possible for your application.

# Generate the token string with 5 seconds of expiration
token = Twilio::JWT::ClientCapability.new(@account_sid, @auth_token, ttl: 5)
Clone this wiki locally