Skip to content

Instantly share code, notes, and snippets.

@dlenski
Last active December 8, 2021 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlenski/63509482df8ec0090e1439fc70ae2c8e to your computer and use it in GitHub Desktop.
Save dlenski/63509482df8ec0090e1439fc70ae2c8e to your computer and use it in GitHub Desktop.
Bash script to parse JSON Web Tokens and pretty-print their contents
#!/bin/bash
# Parses JSON Web Tokens (https://en.wikipedia.org/wiki/JSON_Web_Token)
# and pretty-prints their content.
#
# © 2021 Daniel Lenski <dlenski@gmail.com>, MIT License
jq=$(which jq || echo cat)
for jwt in "$@"; do
IFS=. read -r -a bits <<< "$jwt"
# Convert from URL-safe b64 to "standard" b64, and fix padding
for i in $(seq 0 2); do
bits[$i]=$(tr '_-' '/+' <<< "${bits[$i]}")
case $(( ${#bits[$i]} % 4 )) in
1) bits[$i]+="===" ;;
2) bits[$i]+="==" ;;
3) bits[$i]+="=" ;;
esac
done
echo "Header:"
echo "======="
echo
echo "${bits[0]}" | base64 -d | $jq
echo
echo "Claims:"
echo "======="
echo
echo "${bits[1]}" | base64 -d | $jq
echo
echo "Signature:"
echo "=========="
echo
echo "${bits[2]}" | base64 -d | hexdump -v -e '30/1 "%02X" 1/30 "\n"'
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment