Swimburger

Better Authentication with Twilio API Keys

Niels Swimberghe

Niels Swimberghe - - .NET

Follow me on Twitter, buy me a coffee

An illustration of a lock and a key. The key handle is in the shape of the Twilio logo. Underneath the illustration is text: Better Authentication with Twilio API Keys

This post was originally published at the Twilio Blog. Read the article at Twilio for the best experience.

Twilio generates an Account String Identifier (SID) and an Auth token when you create a Twilio account. This key is for all intents and purposes a master key that can be used to perform any function available in the Twilio API.

Anytime you hand over the Account SID and Auth token to a device or a colleague, you increase the risk of that master key becoming compromised. Luckily Twilio provides capabilities to minimize this risk. This article covers:

  • API Credentials
  • Subaccounts
  • API Keys

In short, this tutorial will help you to stop giving away your Twilio Master Key and start using API Keys.

API Credentials #

When you create a new account or subaccount, Twilio generates an Account SID and Auth token for that account. You can find these API credentials on the dashboard page of your account:

Screenshot of Twilio's account dashboard where the account SID and the auth token is pointed out by arrows.

These credentials are frequently used to communicate with Twilio via the CLI, SDK's, or using the API directly. There is only one auth token by default so you should avoid sharing this auth token to minimize the risk of it becoming compromised. If the auth token is compromised for some reason, rotate it by creating a secondary auth token so that the leaked token becomes useless.

Follow the steps below to create a secondary auth token:

  • Navigate to Settings on the Twilio Console and select General
  • Scroll down to API Credentials
  • Click on the "Request a Secondary Token" link

Screen recording starting from the Twilio Dashboard. Click on settings link. Scroll down to API Credentials. Click on the "Request a Secondary Token" link.

Once you have a secondary token, you can promote this token to the primary token. This will remove the old primary token and render it useless, as seen below.

Screen recording of the API Credentials. The "Promote to Primary" link is clicked on Secondary Token.

Unfortunately, you can only rotate these tokens using the Twilio Console. It is not possible to rotate API Credential tokens using the API. However, you can rotate API Keys which will be covered later in this post.

Subaccounts #

Subaccounts are just like accounts, but they are owned and can be managed by the parent account. Instead of using the API Credentials of the parent account, you can use the API Credentials of the subaccount. If the auth token of the subaccount is compromised, the token cannot be used to access resources of the parent account or other subaccounts.

You can create a subaccount using the Twilio Console by following these steps:

  • Navigate to Settings and select Subaccounts
  • Click on the plus (+) icon if you have other subaccounts already, otherwise click the Create new Subaccount button
  • Enter a friendly name for the subaccount
  • Click the Create button

Screen recording of Twilio Console. User navigating to Settings > Subaccounts. Click the plus-icon, enter a name for the subaccount, and click create.

You can also create subaccounts using Twilio's CLI, SDK, and API as documented in the Twilio Documentation.

API Keys #

API Keys are the preferred way to authenticate to Twilio's services. There are two types of API Keys: Standard and Master.

Standard API Keys give you access to all of the functionality in Twilio's API, except managing API Keys, Account Configuration, and Subaccounts.

Master API Keys have the same access as standard keys, but can also manage API Keys, Account Configuration, and Subaccounts. Master API Keys give you the same level of access as if you were using account API Credentials.

You can create API Keys using the Twilio Console by following these steps:

  • Navigate to Settings and select API Keys
  • Click on the plus (+) icon if you have other API keys already, otherwise click the Create new API Key button
  • Enter a friendly name for your API Key
  • Select whether the key type should be standard or master

Screen recording of Twilio Console. User navigating to Settings > Subaccounts. Click the plus-icon, enter a name for the subaccount, and click create.

You can also create standard API Keys using the CLI, SDK, and API as documented in the Twilio Documentation. You have to be authenticated with the account API Credentials or a Master API Key to manage API Keys.

Rotate API Keys #

One of the advantages of using API Keys instead of API Credentials is that you can use the API to create and delete API Keys. This way you can programmatically rotate API Keys as a preventative measure.
Here is how you would rotate the API Keys using the Twilio CLI and PowerShell:

# Step 0: Install the Twilio CLI and authenticated with account API Credentials or with a Master API Key
# Twilio CLI installation instructions: https://www.twilio.com/docs/twilio-cli/quickstart

# Step 1: Create a new API Key
$NewApiKey = twilio api:core:keys:create -o json | ConvertFrom-Json;
$NewApiKeySid = $NewApiKey.sid;
$NewApiKeySecret = $NewApiKey.secret;

# Step 2: Update your applications to use the new API Key SID and API Key Secret
# --- TO IMPLEMENT BY YOU --- 

# Step 3: Fetch the existing API Key SID (hardcoded for sample)
$OriginalApiKeySid = "[YOUR_API_KEY_SID]";

# Step 4: Delete the old API Key
twilio api:core:keys:remove --sid=$OriginalApiKeySid;

Note: Make sure you have installed the Twilio CLI before running this code.

WARNING: Make sure you develop and test your application to ensure API Key rotation is handled gracefully.

You can create as many API Keys as you need, as opposed to API Credentials where you can only have two (primary and secondary) tokens per account. So instead of passing API Credentials to your teammates and applications, you should give them API Keys. This way you can safely revoke the API Keys when they are no longer used.

Move from API Credentials to API Keys #

If you are already using the Account API Credentials in your code, you can switch to using API Keys with only a few lines of changes.

Please note you'll want to grab some of your account credentials from the Twilio console and save them locally in environment variables for the code to run. For more information on how to do that,  follow the instructions on storing Twilio credentials securely.  

Here's how you would authenticate and send an SMS with the API Credentials using C#:

// Find your Account Sid and Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
string accountSid = Environment.GetEnvironmentVariable("TwilioAccountSid");
string authToken = Environment.GetEnvironmentVariable("TwilioAccountAuthToken");

TwilioClient.Init(
    username: accountSid,
    password: authToken
);

string twilioPhoneNumber = Environment.GetEnvironmentVariable("TwilioPhoneNumber");
string targetPhoneNumber = "[TARGET_PHONE_NUMBER]";

var message = MessageResource.Create(
    body: "Hello World",
    from: new PhoneNumber(twilioPhoneNumber),
    to: new PhoneNumber(targetPhoneNumber)
);
Console.WriteLine(message.Sid);

First, pass in your Account SID as the username parameter, and Auth Token as the password parameter to TwilioClient.Init. Then, send a text message using MessageResource.Create.

Update the parameters passed to TwilioClient.Init to authenticate with your API Key instead of the API Credential:

// Find your Account Sid and Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
string accountSid = Environment.GetEnvironmentVariable("TwilioAccountSid");
string apiKey = Environment.GetEnvironmentVariable("TwilioApiKeySid");
string apiSecret = Environment.GetEnvironmentVariable("TwilioApiKeySecret");

TwilioClient.Init(
    username: apiKey, 
    password: apiSecret, 
    accountSid: accountSid
);

First, pass in the API Key SID to the username parameter instead of the Account SID. Then, pass in the API Key Secret to the password parameter instead of the auth token. Lastly, pass in the Account SID to the accountSid parameter.

Summary #

You can authenticate with Twilio's API using the Account ID as the username and the primary or secondary auth token. If the primary token is compromised, you can promote the secondary token to the primary token which will make the old primary token unusable.

You can protect your credentials by segmenting your account with subaccounts. If an auth token or API Key for a subaccount is compromised, the token can only be used to access resources on the subaccount.

API Keys are now the preferred way to authenticate with Twilio's API. You can create as many API Keys as you need and remove them if they are compromised or no longer used.

Related Posts

Related Posts