#!/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()