Bash script to decode Keycloak JWT

I put together several scripts I found on the internet to have a proper JWT bash decoder:

https://gist.github.com/thomasdarimont/46358bc8167fce059d83a1ebdb92b0e7

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 '_-' '/+' | base64 -d
}

decode_jwt(){
    JWT=`decode_base64_url $(echo -n $2 | cut -d "." -f $1)`
    if [[ "X$(echo $JWT | jq 'has("exp")')" == 'Xtrue' ]]; then
        JWT=`echo $JWT | jq '.exp |= (. | strflocaltime("%Y-%m-%d %H:%M:%S"))'`
    fi
    if [[ "X$(echo $JWT | jq 'has("iat")')" == 'Xtrue' ]]; then
        JWT=`echo $JWT | jq '.iat |= (. | strflocaltime("%Y-%m-%d %H:%M:%S"))'`
    fi
    if [[ "X$(echo $JWT | jq 'has("auth_time")')" == 'Xtrue' ]]; then
        JWT=`echo $JWT | jq '.auth_time |= (. | strflocaltime("%Y-%m-%d %H:%M:%S"))'`
    fi
    echo "$JWT" | jq .
}

# Decode JWT header
alias jwth="decode_jwt 1"

# Decode JWT Payload
alias jwtp="decode_jwt 2"

Leave a Reply

Your email address will not be published. Required fields are marked *