Bash Example


Generating the JWT

A JSON Web Token (JWT) is a standard and secure way to transmit information between parties using JSON. General information about JWTs can be found at jwt.io.

generate_api_token.sh

#!/bin/bash

# Check if the API key is provided as an argument
if [ -z "$1" ]; then
  echo "Usage: $0 API_KEY"
  exit 1
fi

# Define the API key and header/payload
API_KEY="$1"
HEADER='{"alg":"HS256","typ":"JWT"}'
ISSUER="example.com"
SUBJECT="Example JWT"
ISSUED_AT=$(date +%s)

# Construct the payload
PAYLOAD="{\"iss\":\"$ISSUER\",\"sub\":\"$SUBJECT\",\"iat\":$ISSUED_AT}"

# Base64 encode the header and payload
base64_url_encode() {
echo -n "$1" | openssl base64 -e | tr -d '=' | tr '/+' '_-' | tr -d '\n'
}
HEADER_BASE64=$(base64_url_encode "$HEADER")
PAYLOAD_BASE64=$(base64_url_encode "$PAYLOAD")

# Create the signature
SIGNATURE=$(echo -n "$HEADER_BASE64.$PAYLOAD_BASE64" | openssl dgst -sha256 -hmac "$API_KEY" -binary | openssl base64 -e | tr -d '=' | tr '/+' '_-' | tr -d '\n')

# Combine the header, payload, and signature to form the JWT
JWT="$HEADER_BASE64.$PAYLOAD_BASE64.$SIGNATURE"

# Output the JWT
echo "JWT: $JWT"

Sending the request

The code below requires bash script above.

This code requires the API key, the data provider string, a region, and a base64 URL encoded TDS specified as arguments. The script uses these elements to build a JWT and submit a request to the API gateway.

Note that the base64 URL encoded TDS string in this example has been replaced with <BASE64_URLENCODED_TDS> because the encoded TDS is too long to display comfortably here.

send_upload_request.sh

#!/bin/bash

# Echo usage if the three required arguments aren't provided
if [ -z "$4" ]; then
  echo "Usage: $0 SERVER_URL DATA_PROVIDER REGION API_KEY"
  exit 1
fi

# Get variables from arguments
server_url="$1"
data_provider="$2"
region="$3"
api_key="$4"

# Generate JWT
output=$(./generate_api_token.sh "$api_key")

# Extract the JWT, and hash from the output
jwt=$(echo "$output" | grep "JWT" | awk '{ print $2 }')

# The payload is a JSON object with name "tdsContent" and value of the base64 URLencoded TDS
payload='{
  "tdsContent": "<BASE64_URLENCODED_TDS>"
}'

# Send the POST request using curl
curl -i \
  -H "x-salesforce-region: $region" \
  -H "Content-Type: application/json" \
  -H "Authorization: C2C:$jwt" \
  -d "$payload" \
  $server_url/v1/upload-tds-content/$data_provider