Authenticate to the API
Create a JWT request token and authenticate to the API with it, returning a JWT bearer token. Store the bearer token to a file.
1
Assign configuration variables
import jwt
import requests
import random
import time
import json
import os
from http.client import responsesimport requests
url = "https://api.netography.com/api/v1/auth/token"
APPNAME = 'CHANGEME
APPKEY = 'CHANGEME'
SHORTNAME = 'CHANGEME'
SHARED_SECRET = 'CHANGEME'
# path/filename to cache the bearer auth token
CACHE_FILE = '~/.neto.token'#!/bin/bash
# (c) Netography 2023 All Rights Reserved
# blyon
#~~ BEGIN Configuration ~~~
APPNAME=''
APPKEY=''
SHORTNAME=''
SHARED_SECRET=''
API_BASE_URL='https://api.netography.com/api/v1'
# path/filename to cache the JWT auth token
CACHE_FILE='~/.neto.token'
chmod 600 CACHE_FILE
# ~~ END Configuration2
Prepare JWT request payload
payload = {
'iat': int(time.time()),
'jti': random.randint(0,10000000),
'appname': APPNAME,
'appkey': APPKEY,
'shortname': SHORTNAME
}# 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)3
Encode JWT token and create HTTP POST request
token = jwt.encode(payload, SHARED_SECRET, algorithm="HS256")
# Create the HTTP POST request with a JSON payload containing the JWT request token
body = {
'jwt': token
} 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";4
Check for existing token, validate and handle API call
# Cache Bearer token and re-use if not expired
jwt_valid = False
access_token = None
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE) as f:
cache_data = json.load(f)
access_token = cache_data['access_token']
expires_in = cache_data['expires_in']
token_date = os.path.getmtime(CACHE_FILE)
expire_timestamp = token_date + expires_in - 60 # account for some clock skew
if (time.time() <= expire_timestamp):
jwt_valid = True
if not jwt_valid:
try:
resp = requests.post(API_BASE_URL + '/auth/token', json=body)
data = resp.json()
access_token = data['access_token']
with open(CACHE_FILE, 'w') as f:
json.dump(data, f)
except Exception as e:
print(f"{str(resp.status_code)} {responses[resp.status_code]}. Verify your configuration parameters")
{"success":true}Last updated