Rate this page:

How to create a JWT

To use most of the Voximplant HTTP Management API functions, you need to generate a JSON Web Token. Learn how to do that using CLI and a bash script.

Create a token

First, you need to go to the Service accounts section to create a new account and generate a JSON with its credentials (AddGenerate a key). Don't forget about the role, it'll allow using certain features and making certain requests. Then save the result value as a credentials.json file.

Read more about authentication through service accounts.

You can do the same using the CreateKey method of our Management API.

Next, create a token.sh file in the same folder with the following code. Note that the code uses a jq tool that is not a built-in command, so you have to install it manually (download jq here).

#!/usr/bin/env bash

credentials="${PWD}/credentials.json"

account_id=$(cat $credentials | jq -r ".result.account_id")
key_id=$(cat $credentials | jq -r ".result.key_id")
rsa_secret=$(cat $credentials | jq -r ".result.private_key")

timestamp() {
  date +"%s"
}

test_payload=$( jq -n \
    --arg iat "$(timestamp)" \
    --arg iss "$account_id" \
    --arg exp "$(($(timestamp)+3600))" \
    '{
        iat: $iat | tonumber,
        iss: $iss | tonumber,
        exp: $exp | tonumber
    }'
)

set -o pipefail

header_template=$( jq -n \
    --arg typ "JWT" \
    --arg alg "RS256" \
    --arg kid "$key_id" \
    '{typ: $typ, alg: $alg, kid: $kid}'
)

b64enc() { openssl enc -base64 -A | tr '+/' '-_' | tr -d '='; }
json() { jq -c . | LC_CTYPE=C tr -d '\n'; }
rs_sign() { openssl dgst -binary -sha"${1}" -sign <(printf '%s\n' "$2"); }

sign() {

    local secret=$rsa_secret
    algo=RS256
    header=$header_template || return
    payload=$test_payload

signed_content="$(json <<<"$header" | b64enc).$(json <<<"$payload" | b64enc)"

sig=$(printf %s "$signed_content" | rs_sign "${algo#RS}" "$secret" | b64enc)

printf 'Authorization: Bearer %s.%s\n' "${signed_content}" "${sig}"
}

sign
Permissions

You may need to do run chmod +x token.sh to execute the script properly.

Quick copy-paste

You can create a token.sh by downloading the script from our site:

curl https://voximplant.com/assets/images/2020/08/06/jwt.sh --output token.sh

How to use it

Now you can use in your JWT in CLI via curl with the -H key specified. For example, this is how you can request the first 20 users of the specified Voximplant application:

GetUsers

GetUsers