Last active
October 21, 2024 13:19
-
-
Save angelo-v/e0208a18d455e2e6ea3c40ad637aac53 to your computer and use it in GitHub Desktop.
Decode a JWT via command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# will not work in all cases, see https://gist.github.com/angelo-v/e0208a18d455e2e6ea3c40ad637aac53#gistcomment-3439904 | |
function jwt-decode() { | |
sed 's/\./\n/g' <<< $(cut -d. -f1,2 <<< $1) | base64 --decode | jq | |
} | |
JWT=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ | |
jwt-decode $JWT |
What about echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" | cut -d '.' -f 2 | base64 -d
@indian0ch thanks 👍🏻
To get around the broken/unreliable @base64d
from jq
, I got this solution:
jwtd () {
local input="${1:-}"
if [ -z "$input" ]; then
if [ ! -t 0 ]; then
input=$(cat /dev/stdin)
else
echo >&2 '✗ Need an argument or have a piped input!'
return 1
fi
fi
echo "$input" \
| jq -Rrce 'split(".")[1] | . + "=" * (. | 4 - length % 4)' \
| openssl base64 -d -A \
| jq .
}
It will append the =
padding as needed, then pipe into openssl base64 -d -A
, which I found to be more reliable and cross-platform than base64
. I tested this both on Ubuntu and MacOS.
The bash function accepts either a direct param or piped input (e.g., echo 'base64…==' | jwtd
).
@jpbochi Thanks for your script! Why don't you include the tr -- '-_' '+/'
step? openssl needs it right? (e.g. openssl/openssl#17559)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh, beware though that
basenc
complains about missing=
signs, even in--base64url
mode, so you'll also need to suppress stderr.