Skip to content

Instantly share code, notes, and snippets.

@krishnact
Created October 18, 2020 02:07
Show Gist options
  • Save krishnact/30c73caa1ae2555b450c75591b2b3be8 to your computer and use it in GitHub Desktop.
Save krishnact/30c73caa1ae2555b450c75591b2b3be8 to your computer and use it in GitHub Desktop.
Create a JWT token that can be used with InfluxDB API
#!/bin/bash
#Creates JWT token for InfluxDB
INFLUXDB_USER_NAME=$1
NUMBER_OF_DAYS=$2
NOW_SEC=$(date +%s)
NUMBER_OF_SECONDS=$((NUMBER_OF_DAYS*86400))
EXP_TIME=$((NOW_SEC+NUMBER_OF_SECONDS))
SECRET=$3
function usage(){
echo $0 INFLUXDB_USER_NAME NUMBER_OF_DAYS SECRET
}
function createToken(){
# Construct the header
jwt_header=$(echo -n "{'alg':'HS256','typ':'JWT'}" | tr "'" '"'| base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)
# ans: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
# Construct the payload
payload=$(echo -n "{'username':'${INFLUXDB_USER_NAME}', 'exp': ${EXP_TIME}}" | tr "'" '"' | base64 | sed s/\+/-/g |sed 's/\//_/g' | sed -E s/=+$//)
# Convert secret to hex (not base64)
hexsecret=$(echo -n "$SECRET" | xxd -p | paste -sd "")
# For debug, also display secret in base64 (for input into https://jwt.io/)
#echo -n "$secret" | base64
# Calculate hmac signature -- note option to pass in the key as hex bytes
hmac_signature=$(echo -n "${jwt_header}.${payload}" | openssl dgst -sha256 -mac HMAC -macopt hexkey:$hexsecret -binary | base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)
# Create the full token
jwt="${jwt_header}.${payload}.${hmac_signature}"
echo ${jwt}
}
if [ $# -lt 3 ];
then
usage
exit
fi
createToken
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment