Constructing JWTs: Managing access policies for client side requests - Twilio
Register for SIGNAL by 8/31 for $250 off. Register now.

Constructing JWTs: Managing access policies for client side requests

To interact with the JS SDK, we have to generate JWTs from our server code as a means of authorizing which resources the client side application can access. On the server side, we then authenticate a request by checking that the signature of the JWT is signed by the AuthToken of the provided AccountSid.

These allow us a mechanism of authenicating and authorizating your application's API request without exposing your AuthToken on the client side for all to see.

JWT format

JWTs consist of three hashed sections:

  • Header
  • Payload
  • Signature

Let's first go over the two smaller sections of the JWT.

Header

The first part of our JWT token is the header which contains 2 parts:

{
  "typ": "JWT",
  "alg": "HS256"
}

This tells us that this is indeed a JWT and the hashing algorithm used is HS256.

Signature

The third and final part of our JSON Web Token is going to be the signature. This signature is made up of a hash of the following components:

  • Header
  • Payload
  • Secret

In formula terms this is:

hash((hash(header) + hash(payload)), 'secret')

The secret is your AuthToken.

Payload

The payload of the JWT is what defines the access policies for resources.

Access Policy Object

Access Policy Objects are a set of rules that can be applied to an HTTP REST request, authorizing whether this request is allowed to access the API resources. The policy defines which resources and sub-resources are allowed to be accessed, what parameters are expected and allowed, and whether or not the resources and sub-resources are outright forbidden. Access policies will be represented as JSON objects.

The Access Policy Object is a JSON object with the following fields.

Key Description
account_sid The account sid this access policy is acting on behalf.
version The version of the access policy document format being used
friendly_name An optional human readable description string
policies An array of policy rule objects (See Policy Rule Object)
Policy Rule Object

The "policies" array contains policy rule objects.

Key Description
url The URL pattern of of the rule.
method The HTTP method this rule matches.
allow true or false. Does this rule allow access? Defaults to false.
post_filter An object describing the www-form-encoded parameters and values that must be present to match this rule. If undefined, all parameters and values match.
query_filter An object describing the URL query parameters and values that must be present to match this rule. If undefined, all parameters and values match.
url

The "url" key defines a literal or pattern that will be matched against the request's URL.
This field should contain the URL without query parameters and may either be a literal string or end in a wildcard string. Literal strings must exactly match the request URL for this rule to match. There are two types of wildcard strings:

  • Immediate child wildcard (URLs ending in "/*").
  • Recursive wildcard (URLs ending in "/**").

Immediate child wildcards cause a rule to match the next step in the path, but no further.

For example:

  • https://taskrouter.twilio.com/v1/Workspaces/*

Matches:

  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx

But not these URLs:

  • https://taskrouter.twilio.com/v1/Workspaces/
  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx/TaskQueues

Recursive wildcards cause a URL to match any child URL of this path.

For example:

  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**

Matches:

  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx/TaskQueues
  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx/TaskQueues/WQxxx
  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx/Workers/WKxxx/Statistics
  • https://taskrouter.twilio.com/v1/Workspaces/WSxxx/Statistics

But not:

  • https://taskrouter.twilio.com/v1/Workspaces/WSxxxx
  • https://taskrouter.twilio.com/v1/Workspaces

Multiple Rule Matching

  • For requests that match multiple rules, the rule that is most specific takes priority.
  • Longer, more specific paths take priority over less specific.
  • If the paths are the same, rules with filters take priority over rules without filters.
  • Directly conflicting rules are considered invalid and should be detected and rejected by the access policy parser.
method

The HTTP method this rule applies to: GET, POST, DELETE

allow

Allow may have a value of true or false. If the matching rule has an allow value of "true", the request is authorized. If the allow value is false, the request is explicitly rejected. The default for all rules is "false".

post_filter and query_filter

The post_filter and query_filter fields are used to match parameters provided in either the query string or www-form-post-params. The value is an object whose keys are the parameter names, and values are either a string literal that must be matched, or a matcher object that describes how the key is matched in more detail. Both post and query filters use the same format.

String Literal Example

"post_filter": {
    "FriendlyName": "Alice"
}

This would match a request that contained a single www-form-encoded parameter FriendlyName with the value Alice. If the request contained any other form parameters, it would not match this rule.

Matcher Object Example

"post_filter": {
   "FriendlyName": {"required": true},
   "Status": {"required": false},
   "Foo": {"required": false, "value": "bar"}
}

Matcher objects allow for more complex matching rules. In the above example, the field FriendlyName is required, but will match any provided value. The field Status is optional, meaning this rule will match if its provided or not. If it is provided, any value will be allowed. The field "Foo" is optional as well, but if it is provided, it must have the value "bar".

Matcher Object

Key Description
required is this param required, true or false
value optional. if present, the value is a string literal that the value of the field must match. If not present, the field will match any value.

Standard JWT Payload fields

In addition to our list of policies, we need to define the following in the payload:

  • iss: The issuer of the token (AccountSid)
  • exp: When the token will expire (TimeStamp in seconds since epoch)
  • account_sid: Account owner of the token
  • workspace_sid: Workspace owner of the token
  • channel: The channel to receive updates on and post API requests to.

If you are defining a Worker, you will also need to define the following:

  • channel: WSxxx
  • worker_sid: WKxxx

If you are defining a Workspace, you will also need to define the following:

  • channel: WSxxx

Required Policies

Two required policies in your JWT include the ability to connect to a web-socket channel and post messages on that web-socket to hit the REST API. These are required since we want to authenicate and authorize the opening a websocket in the first place. Subsequent events to GET, POST or DELETE to other APIs will utilize this websocket.

For example:

{
    "url": "https://event-bridge.twilio.com/v1/wschannels/AccountSid/Channel",
    "method": "GET",
    "allow": true
},
{
    "url": "https://event-bridge.twilio.com/v1/wschannels/AccountSid/Channel",
    "method": "POST",
    "allow": true
}

Deconstructing a helper library method to Policy Object

Let's take an example using the helper library and see what this breaks down to as a policy object:

<?php
$workspaceCapability = new Services_Twilio_TaskRouter_Capability($accountSid, $authToken, $workspaceSid, $workspaceSid);
$workspaceCapability->allowFetchSubresources();
$workspaceCapability->allowDeleteSubresources();
$workspaceCapability->allowUpdatesSubresources();
$workspaceToken = $workspaceCapability->generateToken();

The policy object would look like the following:

{
    "url": "https://event-bridge.twilio.com/v1/wschannels/ACxxx/WSxxx",
    "method": "GET",
    "allow": true
},
{
    "url": "https://event-bridge.twilio.com/v1/wschannels/ACxxx/WSxxx",
    "method": "POST",
    "allow": true
},
{
    "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx",
    "method": "GET",
    "allow": true
},
{
    "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**",
    "method": "GET",
    "allow": true
},
{
    "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**",
    "method": "POST",
    "allow": true
},
{
    "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**",
    "method": "DELETE",
    "allow": true
}

In total, the JWT payload would decode to:

{
  "version": "v1",
  "friendly_name": "WSxxx",
  "policies": [
    {
      "url": "https://event-bridge.twilio.com/v1/wschannels/ACxxx/WSxxx",
      "method": "GET",
      "allow": true
    },
    {
      "url": "https://event-bridge.twilio.com/v1/wschannels/ACxxx/WSxxx",
      "method": "POST",
      "allow": true
    },
    {
      "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx",
      "method": "GET",
      "allow": true
    },
    {
      "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**",
      "method": "GET",
      "allow": true
    },
    {
      "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**",
      "method": "DELETE",
      "allow": true
    },
    {
      "url": "https://taskrouter.twilio.com/v1/Workspaces/WSxxx/**",
      "method": "POST",
      "allow": true
    }
  ],
  "iss": "ACxxx",
  "exp": 1432251317,
  "account_sid": "ACxxx",
  "channel": "WSxxx",
  "workspace_sid": "WSxxx"
}

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.