shell-scripts/jwt-decode.sh
c47 7df20ceb47 Fix typo and add script output to comments
Fixed a typo in the description comment and added
the script's output to the comment as well to have
the results saved somewhere.
2023-10-30 08:16:01 +01:00

65 lines
1.8 KiB
Bash

#!/bin/bash
#
# First search result I read was this blogpost:
#
# https://prefetch.net/blog/2020/07/14/decoding-json-web-tokens-jwts-from-the-linux-command-line/
#
# where I found a link to a solution with sed:
#
# https://gist.github.com/angelo-v/e0208a18d455e2e6ea3c40ad637aac53
#
# which I prefer, because I like sed very much and I simplified that as you can read below at
# 'sed method' section.
# But as I read the comments it turned out that working on this with linux coreutils' base64 is
# fragile as it doesn't support base64url encoding. In the following comment:
#
# https://gist.github.com/angelo-v/e0208a18d455e2e6ea3c40ad637aac53?permalink_comment_id=3439919#gistcomment-3439919
#
# a solution with pure jq was provided where they replace characters which was found to be good.
# It would be easy to replace the characters with sed, but I currently don't know if that really
# gets around the problem with using base64 from coreutils, so I keep both solutions here.
#
# At the time of initialization of this repo and thus this script the sed method prints more information
# then the jq method
# 1) sed method:
#
#{
# "alg": "HS256",
# "typ": "JWT"
#}
#{
# "sub": "1234567890",
# "name": "John Doe",
# "admin": true
#}
#
#
#2) Pure jq method
#
#{
# "sub": "1234567890",
# "name": "John Doe",
# "admin": true
#}
#
JWT=${1:-eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ}
echo -e "## JWT decode of \n${1:-example token:\n\t${JWT}}"
echo
echo
echo '1) sed method'
echo
sed -e 's/^\([^.]\+\.\)\([^.]\+\)\..*/\1\2/' -e 's/\./\n/g' <(echo ${JWT}) | \
base64 --decode | \
jq
echo
echo
echo '2) Pure jq method'
echo
echo ${JWT} | jq -R 'gsub("-";"+") | gsub("_";"/") | split(".") | .[1] | @base64d | fromjson'