Generate Capability Tokens

Twilio Client allows you to make and receive connections in the browser. You can place a call to a phone on the PSTN network, all without leaving your browser. See the Twilio Client Quickstart to get up and running with Twilio Client.

Capability tokens are used by Twilio Client to provide connection security and authorization. The Capability Token documentation explains in depth the purpose and features of these tokens.

Twilio::Util::Capability is responsible for the creation of these capability tokens. You’ll need your Twilio AccountSid and AuthToken.

require 'twilio-ruby'

# Find these values at twilio.com/user/account
account_sid = "AC123123"
auth_token = "secret"

@capability = Twilio::Util::Capability.new account_sid, auth_token

You can also configure capability tokens using the top level configure method, like so:

require 'twilio-ruby'

Twilio.configure do |config|
  config.account_sid = "ACXXXXXXXXXXXXXXXXX"
  config.auth_token = "YYYYYYYYYYYYYYYYYY"
end

@capability = Twilio::Util::Capability.new

Allow Incoming Connections

Before a device running Twilio Client can recieve incoming connections, the instance must first register a name (such as “Alice” or “Bob”). The allow_client_incoming() method adds the client name to the capability token.

@capability.allow_client_incoming("Alice")

Allow Outgoing Connections

To make an outgoing connection from a Twilio Client device, you’ll need to choose a Twilio Application to handle TwiML URLs. A Twilio Application is a collection of URLs responsible for outputting valid TwiML to control phone calls and messages.

# Twilio Application Sid
application_sid = "APabe7650f654fc34655fc81ae71caa3ff"
@capability.allow_client_outgoing(application_sid)

Add Parameters to an Outgoing Scope

You can send parameters to your Twilio Application’s VoiceUrl by passing a hash to #allow_client_outgoing. Here we pass along a hypothetical user id.

application_sid = "APabe7650f654fc34655fc81ae71caa3ff"
params = {'user_id' => @user.id}

# Allow outgoing calls to an application and pass the user id to your server.
@capability.allow_client_outgoing(application_sid, params)

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.

Generate a Token

@token = @capability.generate()

By default, this token will expire in one hour. If you’d like to change the token expiration, generate() takes an optional ttl argument.

@token = @capability.generate(ttl=600)

This token will now expire in 10 minutes. If you haven’t guessed already, ttl is expressed in seconds.