Skip to contentSkip to navigationSkip to topbar
On this page

Access Tokens


Access Tokens are short-lived tokens that you use to authenticate Twilio client-side SDKs like Voice, Conversations, Sync, and Video.

You create them on your server to verify a user's identity and grant access to client API features. All tokens have a limited lifetime, configurable for up to 24 hours. However, a best practice is to generate Access Tokens for the shortest amount of time feasible for your application.


Contents

contents page anchor

Anatomy of an Access Token

token-anatomy page anchor

Each Access Token is a JSON Web Token(link takes you to an external page) (JWT), an encoded JSON object with three parts: the header, the payload, and the signature. The following is an example Access Token generated for Conversations.

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTS3h4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4LTE0NTA0NzExNDciLCJpc3MiOiJTS3h4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4Iiwic3ViIjoiQUN4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eCIsIm5iZiI6MTQ1MDQ3MTE0NywiZXhwIjoxNDUwNDc0NzQ3LCJncmFudHMiOnsiaWRlbnRpdHkiOiJ1c2VyQGV4YW1wbGUuY29tIiwiaXBfbWVzc2FnaW5nIjp7InNlcnZpY2Vfc2lkIjoiSVN4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eCIsImVuZHBvaW50X2lkIjoiSGlwRmxvd1NsYWNrRG9ja1JDOnVzZXJAZXhhbXBsZS5jb206c29tZWlvc2RldmljZSJ9fX0.IHx8KeH1acIfwnd8EIin3QBGPbfnF-yVnSFp5NpQJi0

If you inspect it with the debugger at jwt.io(link takes you to an external page), you can further explore its content.

Header

jwt-header page anchor
1
{
2
"typ": "JWT",
3
"alg": "HS256",
4
"cty": "twilio-fpa;v=1"
5
}

The header section encodes the format of the token:

  • typ is the type of token. Its value must be "JWT".
  • alg is the algorithm used to encode the token. Its value must be "HS256".
  • cty is the content type and encodes the version of the Access Token. Its value must be "twilio-fpa;v=1".
1
{
2
"jti": "SKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-1450471147",
3
"iss": "SKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
4
"sub": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
5
"iat": 1450471147,
6
"nbf": 1450471147,
7
"exp": 1450474747,
8
"grants": {
9
"identity": "user_name",
10
"chat": {
11
"service_sid": "ISxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
12
}
13
}
14
}

The payload section describes the authorization granted:

  • jti is a unique identifier for the token. Your application can choose this identifier. The default helper library implementation includes the SID of the API key used to generate the token and a unique random string.
  • iss is the issuer — the API key containing the secret used to sign the token.
  • sub is the SID of the Twilio Account to which access is scoped.
  • iat is the timestamp at which the token was issued.
  • nbf is an optional timestamp, before which the token will NOT be accepted.
  • exp is the timestamp at which the token will expire. Tokens have a maximum age of 24 hours.
  • grants is the list of permissions that the token grants. Grant properties and values will depend on the Twilio product and the needs of your specific use case.

The signature section is a signed hash that serves to prove the authenticity of the token. It is the result of hashing the JWT header and payload together with your API key secret, which should only be known to your application and Twilio.


Create Access Tokens

creating-tokens page anchor

Twilio Access Tokens are based on the JSON Web Token(link takes you to an external page) standard.

You can use one of Twilio's Helper Libraries to create Access Tokens quickly and programmatically.

Step 1: Find your Account SID

step-1-account-sid page anchor

Every Access Token requires your Account SID, which you can find in your Twilio Console(link takes you to an external page). This is how the AccessToken will tie a user's activity to a specific Twilio account.

Step 2: Create an API Key and Secret

step-2-api-key page anchor

Next, you need to create an API key. You can create API keys from the Twilio Console(link takes you to an external page) or with the REST API.

Note: You can create Access Tokens using Main and Standard API Keys. Creating Access Tokens is not yet supported with Restricted API Keys.

(warning)

Warning

If you are creating a key to use with Twilio Video, you must create it in the US1 Region. Learn more in the Twilio Video documentation.

When you create the API key, you'll be shown the key's secret, which is used to sign the Access Token. For security, you will only be shown the secret at this time, so you need to store it with the key's SID in a secure location for the next step.

Step 3: Generate an Access Token

step-3-generate-token page anchor

Now use the information gathered in steps 1 and 2 to generate an Access Token using a Twilio Helper Library.

When creating an Access Token, you must provide:

  • Your Twilio Account SID
  • The API key SID and API key secret from Step 2

You can also optionally provide any of the following JWT configuration values.

ParameterDescriptionExample
identityThe identity to associate with the Access Token. Typically, this will be a username in your system. Voice tokens may only contain alpha-numeric and underscore characters.user_name
ttlTime to live for the token, in seconds.3600
nbfToken not before time, or the time before which the token will NOT be accepted. Values are in Epoch time.1615404972
regionThe intended Twilio Region for the token. Currently only supported for Voice tokens.us1

Each Twilio product will also require at least one "grant", which will provide product-specific abilities to the user associated with an Access Token.

(warning)

Warning

Programmable Voice access tokens limit the number of concurrent sessions for a given identity to ten. When the 11th instance of the identity is registered the oldest registration is removed.

Use a Helper Library to create Access Tokens

use-a-helper-library-to-create-access-tokens page anchor

Below are code samples for creating Access Tokens with Twilio Helper Libraries. Click on a product below to jump to the related code samples.

Create an Access Token for Conversations

create-an-access-token-for-conversations page anchor

The Conversations SDK requires each Access Token to contain a ChatGrant. Each ChatGrant must contain the SID for your Conversation Service. Each Access Token will also contain an identity grant that associates an Access Token with a specific user.

Create an Access Token for ConversationsLink to code sample: Create an Access Token for Conversations
1
const AccessToken = require('twilio').jwt.AccessToken;
2
const ChatGrant = AccessToken.ChatGrant;
3
4
// Used when generating any kind of tokens
5
// To set up environmental variables, see http://twil.io/secure
6
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
7
const twilioApiKey = process.env.TWILIO_API_KEY;
8
const twilioApiSecret = process.env.TWILIO_API_SECRET;
9
10
// Used specifically for creating Chat tokens
11
const serviceSid = process.env.TWILIO_CHAT_SERVICE_SID;
12
const identity = 'user@example.com';
13
14
// Create a "grant" which enables a client to use Chat as a given user,
15
// on a given device
16
const chatGrant = new ChatGrant({
17
serviceSid: serviceSid,
18
});
19
20
// Create an access token which we will sign and return to the client,
21
// containing the grant we just created
22
const token = new AccessToken(
23
twilioAccountSid,
24
twilioApiKey,
25
twilioApiSecret,
26
{identity: identity}
27
);
28
29
token.addGrant(chatGrant);
30
31
// Serialize the token to a JWT string
32
console.log(token.toJwt());

Create an Access Token for Voice

create-an-access-token-for-voice page anchor
1
const AccessToken = require('twilio').jwt.AccessToken;
2
const VoiceGrant = AccessToken.VoiceGrant;
3
4
// Used when generating any kind of tokens
5
// To set up environmental variables, see http://twil.io/secure
6
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
7
const twilioApiKey = process.env.TWILIO_API_KEY;
8
const twilioApiSecret = process.env.TWILIO_API_SECRET;
9
10
// Used specifically for creating Voice tokens
11
const outgoingApplicationSid = 'APxxxxxxxxxxxxx';
12
const identity = 'user';
13
14
// Create a "grant" which enables a client to use Voice as a given user
15
const voiceGrant = new VoiceGrant({
16
outgoingApplicationSid: outgoingApplicationSid,
17
incomingAllow: true, // Optional: add to allow incoming calls
18
});
19
20
// Create an access token which we will sign and return to the client,
21
// containing the grant we just created
22
const token = new AccessToken(
23
twilioAccountSid,
24
twilioApiKey,
25
twilioApiSecret,
26
{identity: identity}
27
);
28
token.addGrant(voiceGrant);
29
30
// Serialize the token to a JWT string
31
console.log(token.toJwt());

The Voice SDKs require each Access Token to contain an identity grant and a VoiceGrant. The identity grant is what associates an Access Token with a specific user.

Each VoiceGrant contains the following parameters:

ParameterTypeDescription
incomingAllowBooleanIndicates whether or not the endpoint associated with this Access Token is allowed to receive incoming calls as the identity included in the Access Token
outgoingApplicationSidstringThe SID of the TwiML App that Twilio will look to when making outgoing calls. (Note: This is required for using any of the Voice SDKs.)
outgoingApplicationParamsobjectRequest parameters to send to the TwiML Application for outgoing calls
pushCredentialSidstringThe SID of the Push Credential to use when registering to receive incoming call notifications (Mobile SDKs only)

The payload of a decoded Voice AccessToken will look something like the following:

1
{
2
"jti": "SKxxxx...-1643993631",
3
"grants": {
4
"identity": "alice",
5
"voice": {
6
"incoming": {
7
"allow": true
8
},
9
"outgoing": {
10
"application_sid": "APxxxx..."
11
},
12
"push_credential_sid": "CRxxxx..."
13
}
14
},
15
"iat": 1643993631,
16
"exp": 1643997231,
17
"iss": "SKxxxx...",
18
"sub": "ACxxxx..."
19
}

Create an Access Token for Video

create-an-access-token-for-video page anchor
(warning)

Warning

The API Key you use to create an Access Token for Twilio Video must be in the US1 region.

The Video SDKs require each Access Token to contain an identity grant and a VideoGrant.

The identity grant is what associates an Access Token with a specific user.

Each VideoGrant contains an optional room parameter for a specific Room name or SID, which indicates the holder of the Access Token may only connect to the indicated Room.

Learn more about Video Access Tokens on the User Identity & Access Tokens page.

1
const AccessToken = require('twilio').jwt.AccessToken;
2
const VideoGrant = AccessToken.VideoGrant;
3
4
// Used when generating any kind of tokens
5
// To set up environmental variables, see http://twil.io/secure
6
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
7
const twilioApiKey = process.env.TWILIO_API_KEY;
8
const twilioApiSecret = process.env.TWILIO_API_SECRET;
9
10
const identity = 'user';
11
12
// Create Video Grant
13
const videoGrant = new VideoGrant({
14
room: 'cool room',
15
});
16
17
// Create an access token which we will sign and return to the client,
18
// containing the grant we just created
19
const token = new AccessToken(
20
twilioAccountSid,
21
twilioApiKey,
22
twilioApiSecret,
23
{identity: identity}
24
);
25
token.addGrant(videoGrant);
26
27
// Serialize the token to a JWT string
28
console.log(token.toJwt());

Create an Access Token for Sync

create-an-access-token-for-sync page anchor

Sync requires your Access Token to contain an identity grant and a SyncGrant. The identity grant is what associates an Access Token with a specific user.

The SyncGrant requires a serviceSid parameter containing the SID for your Sync Service.

Learn more about Sync Access Tokens on the Issuing Sync Tokens page.

1
const AccessToken = require('twilio').jwt.AccessToken;
2
const SyncGrant = AccessToken.SyncGrant;
3
4
// Used when generating any kind of tokens
5
// To set up environmental variables, see http://twil.io/secure
6
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
7
const twilioApiKey = process.env.TWILIO_API_KEY;
8
const twilioApiSecret = process.env.TWILIO_API_SECRET;
9
const twilioSyncService = process.env.TWILIO_SYNC_SERVICE_SID;
10
11
// Used specifically for creating Sync tokens
12
const identity = 'user';
13
14
// Create a "grant" which enables a client to use Sync as a given user
15
const syncGrant = new SyncGrant({
16
serviceSid: twilioSyncService,
17
});
18
19
// Create an access token which we will sign and return to the client,
20
// containing the grant we just created
21
const token = new AccessToken(
22
twilioAccountSid,
23
twilioApiKey,
24
twilioApiSecret,
25
{ identity: identity }
26
);
27
token.addGrant(syncGrant);
28
29
// Serialize the token to a JWT string
30
console.log(token.toJwt());

Now you're ready to use your token. For client-side SDKs like Conversations, Voice, and Video, you will need to get the stringified token to your client-side code via Ajax or some other means.

Refer to the Identity and Access Tokens guides in the product documentation for Video, Conversations, Sync for more details.


Managing the lifecycle of Access Tokens

managing-lifecycle page anchor

You can use API keys to manage the lifecycle of Access Tokens.

Since each Access Token was created using an API Key, you can delete the API key to revoke all of the Access Tokens related to that API Key.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.