Skip to content

Instantly share code, notes, and snippets.

@jbayer
Created May 19, 2025 15:20
Show Gist options
  • Save jbayer/2e7d784701a5b191051787036906f570 to your computer and use it in GitHub Desktop.
Save jbayer/2e7d784701a5b191051787036906f570 to your computer and use it in GitHub Desktop.
Read Base64 encoded JWT
#!/bin/bash
# Split the JWT into parts (header.payload.signature)
# TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvbiBEb2UiLCJpYXQiOjE1MTYyMzkwMjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
# Name of the required environment variable
REQUIRED_VAR="TOKEN"
# Check if the variable is not set or empty
if [[ -z "${!REQUIRED_VAR}" ]]; then
echo "❌ Error: Environment variable '$REQUIRED_VAR' is required but not set."
echo ""
echo "👉 Please set it before running this script. Example:"
echo ""
echo " export $REQUIRED_VAR=your_base64_jwt_token_here"
echo " ./$(basename "$0")"
echo ""
exit 1
fi
# Extract the header
header=$(echo "$TOKEN" | cut -d '.' -f1)
# Convert Base64URL to standard Base64
header_b64=$(echo "$header" | tr '_-' '/+')
# Add padding if needed
remainder=$((${#header_b64} % 4))
if [ $remainder -eq 2 ]; then
header_b64="${header_b64}=="
elif [ $remainder -eq 3 ]; then
header_b64="${header_b64}="
fi
# Decode Header
echo "$header_b64" | base64 -d | jq
# Extract the body
body=$(echo "$TOKEN" | cut -d "." -f2)
# Convert Base64URL to standard Base64
body_b64=$(echo "$body" | tr '_-' '/+')
# Add padding if needed
remainder=$((${#body_b64} % 4))
if [ $remainder -eq 2 ]; then
body_b64="${body_b64}=="
elif [ $remainder -eq 3 ]; then
body_b64="${body_b64}="
fi
# Decode body
echo "$body_b64" | base64 -d | jq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment