Files
python-helpers/python_helpers/cli/token_decoder.py
T
slawek 9f56b3ee19 Add initial implementation of Python helpers and CLI tools
- Create .gitignore to exclude build artifacts
- Add README.md with project description and installation instructions
- Implement pyproject.toml for package metadata and script entry points
- Add console output helpers for command-line scripts
- Implement environment file loading functionality
- Add JSON file I/O helpers
- Create token decoder CLI for decoding JWT claims
- Implement serve-markdown CLI for serving Markdown files as HTML
2026-09-06 19:15:54 +02:00

74 lines
1.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Decode a JWT's claims, without verifying its signature."""
import argparse
import base64
import json
import sys
from python_helpers.console import fail
EXAMPLES = """
Examples:
%(prog)s token.txt
echo "$TOKEN" | %(prog)s
This command will:
1. Read a JWT from the given file, or from stdin if no file is given
2. Decode its payload claims, without verifying its signature
3. Print the claims as JSON
"""
def decode_jwt_claims(token):
"""Decode a JWT's payload claims, without verifying its signature.
Args:
token: a JSON Web Token (JWT) string.
Returns:
The decoded claims as a dict.
"""
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
return json.loads(base64.urlsafe_b64decode(payload))
def build_parser():
"""Build the argparse parser for this script."""
parser = argparse.ArgumentParser(
description="Decode a JWT's claims, without verifying its signature.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=EXAMPLES,
)
parser.add_argument(
"token_file",
nargs="?",
help="Path to a file containing a JWT; reads from stdin if omitted",
)
return parser
def main():
"""Parse arguments and print the decoded claims of the given (or piped-in) token."""
args = build_parser().parse_args()
if args.token_file:
try:
with open(args.token_file, encoding="utf-8") as token_file:
token = token_file.read().strip()
except OSError as error:
fail(f"Could not read '{args.token_file}': {error}")
else:
token = sys.stdin.read().strip()
if not token:
fail("No token given")
print(json.dumps(decode_jwt_claims(token), indent=2))
if __name__ == "__main__":
main()