curl: Authenticate to API using NETOSECRET
Shell script that takes a NETOSECRET API key, builds a JWT request token, authenticates to the Fusion API, and output the bearer token to use in subsequent API calls.
1
✅ Check Required Tools
Ensures jq, openssl, and base64 are installed. Exits with an error message if any are missing.
#!/bin/bash
# Step 1: Check prerequisites
for cmd in jq openssl base64; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "❌ Required command '$cmd' not found. Please install it and retry." >&2
exit 1
fi
done2
🔐 Load NETOSECRET Environment Variable
Checks if $NETOSECRET is set. If not, explains how to set it and exits.
# Step 2: Retrieve and validate NETOSECRET
if [ -z "$NETOSECRET" ]; then
echo "❌ Environment variable NETOSECRET is not set."
echo "To retrieve this value from the Fusion Portal, see:"
echo "https://docs.netography.com/reference/create-a-netography-api-key"
exit 1
fi
netosecret=$NETOSECRET3
📦 Decode and Extract Secret Fields
Decodes the base64 JSON and extracts appname, appkey, shortname, and sharedsecret using jq.
# Step 3: Decode the secret and extract fields using jq
decoded=$(echo "$netosecret" | base64 -d)
appname=$(echo "$decoded" | jq -r .appname)
appkey=$(echo "$decoded" | jq -r .appkey)
shortname=$(echo "$decoded" | jq -r .shortname)
sharedsecret=$(echo "$decoded" | jq -r .sharedsecret)
url=$(echo "$decoded" | jq -r .url)4
🏗️ Construct JWT Header and Payload
Prepares the standard JWT header and payload with timestamps and identifiers.
# Step 4: Create JWT header and payload
header='{"alg":"HS256","typ":"JWT"}'
iat=$(date +%s)
jti=$((RANDOM * RANDOM))
payload=$(jq -nc \
--arg appname "$appname" \
--arg appkey "$appkey" \
--arg shortname "$shortname" \
--argjson iat "$iat" \
--argjson jti "$jti" \
'{iat:$iat,jti:$jti,appname:$appname,appkey:$appkey,shortname:$shortname}')5
6
7
✍️ Sign the JWT Payload
Uses openssl to sign the header and payload with the shared secret (HMAC-SHA256).
# Step 7: Create JWT signature
signature=$(printf "%s.%s" "$header64" "$payload64" \
| openssl dgst -sha256 -hmac "$sharedsecret" -binary \
| base64url)
jwt="${header64}.${payload64}.${signature}"8
📤 Create JWT Request Token
Concatenates the parts into the final JWT request token to send to API.
# Step 8: Request bearer token
token_response=$(curl -s -X POST \
--url "${url}/auth/token" \
-H "accept: application/json" \
-H "content-type: application/json" \
-d "$(jq -nc --arg jwt "$jwt" '{jwt:$jwt}')")9
Last updated