JWT authentication (shell)
We have provided a shell script designed to authenticate with the Netography API using a JSON Web Token (JWT) and cache the resulting access token for future use.
In the Netography portal, navigate to Account Settings > API Keys, and create an API Key. The values from that page should be used to update the following in the script:
APPNAME
# API Key NameAPPKEY
# API Key SecretSHARED_SECRET
# Account Shared Secret (viewable on the API Keys page)- Additionally, update the
SHORTNAME
(visible on the Account Settings page)
#!/bin/bash
# (c) Netography 2023 All Rights Reserved
# blyon
#~~ BEGIN Configuration ~~~
APPNAME='App name from Portal'
APPKEY='Appkey from portal'
SHORTNAME='company short name'
SHARED_SECRET='Shared secret from portal'
API_BASE_URL='https://api.netography.com/api/v1'
# path/filename to cache the JWT auth token (may not be secure to store data in tmp)
CACHE_FILE='/tmp/neto-jwt'
# ~~ END Configuration
# Functin to create proper encoding
base64_encode() {
local input="$1"
local encoded=$(printf '%s' "$input" | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n')
echo "$encoded"
}
# Cache Bearer token and re-use if not expired
jwt_valid=false
access_token=''
if [ -f "$CACHE_FILE" ]; then
cache_data=`cat $CACHE_FILE`
access_token=$(echo "$cache_data")
jwt_valid=true
fi
if [[ $jwt_valid == false ]]; then
# Generate the JWT request token
DATE=`date +%s`
payload=$(printf '%s' '{"iat":"'"$DATE"'","jti":"'"$RANDOM"'","appname":"'"$APPNAME"'","appkey":"'"$APPKEY"'","shortname":"'"$SHORTNAME"'"}' )
# Static header fields.
header='{
"typ": "JWT",
"alg": "HS256"
}'
# Create body
header_base64=$(base64_encode "$header")
payload_base64=$(base64_encode "$payload")
header_payload_base64=$(printf '%s' $header_base64.$payload_base64)
signature=$(printf '%s' $header_payload_base64 | openssl dgst -sha256 -hmac "$SHARED_SECRET" -binary | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n')
body="$header_base64.$payload_base64.$signature";
# Create the HTTP POST request with a JSON payload containing the JWT request token
post=$(echo "{ "'"jwt"'": \"$body\" }" )
resp=$(curl -s -X POST "$API_BASE_URL/auth/token" -H "Content-Type: application/json" -d "$post")
if ! echo "$resp" | grep -q 'access_token'; then
if echo "$resp" | jq -r '.message' 1>/dev/null 2>&1; then
echo "Authentication Error: $(echo "$resp" | jq -r '.message')"
else
echo "Authentication Error: access_token not found in response"
fi
exit 1
fi
access_token=$(echo "$resp" | jq -r '.access_token')
fi
echo "bearer: $access_token"
echo -n $access_token>$CACHE_FILE
Updated 3 months ago