Thursday, February 27, 2020

Call Oauth Token server and decode JWT (Json Web Token) from command line

function jwt-d() {
     sed 's/\./\n/g' <<< $(cut -d. -f1,2 <<< $1) | base64 --decode | jq
}

decode_base64_url() {
    local len=$((${#1} % 4))
    local result="$1"
    if [ $len -eq 2 ]; then
         result="$1"'=='
    elif [ $len -eq 3 ];
         then result="$1"'='
fi
#echo "$result" | tr '_-' '/+' | openssl enc -d -base64
echo "$result" | tr '_-' '/+' | base64 -d
}

decode_jwt(){

    IFS=. read -r jwt_header jwt_body jwt_trail<<<$(echo -n $1)
    echo -e "HEADER:"
    decode_base64_url ${jwt_header} | jq .
    echo -e "\nBODY:"
    decode_base64_url ${jwt_body} | jq --arg TZ $(date +"%Z") 'if .exp then (.expStr = (.exp + 3600*($TZ|tonumber) |gmtime|strftime("%d %B %Y - %H:%M:%S"))) | del (.exp) else . end | if .ia
t then (.iatStr = (.iat + 3600*($TZ|tonumber) |gmtime|strftime("%d %B %Y - %H:%M:%S"))) | del(.iat) else . end'

    echo -e "TRAIL: \n\n${jwt_trail}"
}

alias jwtd="decode_jwt"

sts_token() {
    local tk=$(curl -k -X POST 'https://geratoken.com.br/api/token' --header 'Content-Type: application/x-www-form-urlencoded' --header 'x-empresa-apikey: XXXXXXXX' --header 'x-empresa-correlationID: 123' --header 'x-empresa-flowID: 456' --data-urlencode 'client_id=XXXXXXX' --data-urlencode 'grant_type=client_credentials'
--data-urlencode 'client_secret=XXXXXXX' --cert ~/certificados/mycert.crt --key ~/certificados/mycerkey.key | jq -r .access_token)
    echo "TOKEN: " ${tk}
    jwtd ${tk}
}

No comments:

Blog Archive