Skip to content

Instantly share code, notes, and snippets.

@leehambley
Created September 23, 2020 13:20
Show Gist options
  • Save leehambley/c752012c4e2b7d35fbab67005d2160cd to your computer and use it in GitHub Desktop.
Save leehambley/c752012c4e2b7d35fbab67005d2160cd to your computer and use it in GitHub Desktop.
Example for decoding a JWT Payload with your Shell (bash, zsh...)

Setup

Add this to your .profile, .bashrc, .zshrc...

_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
}

# $1 => JWT to decode
# $2 => either 1 for header or 2 for body (default is 2)
decode_jwt() { _decode_base64_url $(echo -n $1 | cut -d "." -f ${2:-2}) | jq .; }

Usage

MY_JWT="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"

# decodes body (default behaviour)
decode_jwt $MY_JWT
# # decodes header
# decode_jwt $MY_JWT 1

Output

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment