Last active
May 14, 2019 08:01
-
-
Save etchegom/e8faf565aa4336894715639e98deb08d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import jwt | |
import logging | |
from pprint import pformat | |
""" | |
Decode a JWT token, encoded with alogorithm RSA256. | |
- validate signature | |
- verify expiration date | |
- verify audience | |
Python requirements: | |
- PyJWT==1.7.1 | |
- cryptography==2.6.1 | |
""" | |
logger = logging.getLogger(__name__) | |
def decode_token(token, key, audience, issuer): | |
""" | |
Validate and decode a JWT token, using RSA256 algorithm. | |
:param token: the token to decode | |
:param key: a valid public key | |
:param audience: audience expected value | |
:param issuer: issuer expected value | |
:return: the token payload | |
""" | |
try: | |
payload = jwt.decode( | |
jwt=token, | |
key=key, | |
algorithms='RS256', | |
audience=audience, | |
issuer=issuer, | |
options={ | |
'verify_signature': True, | |
'verify_exp': True, | |
'verify_nbf': True, | |
'verify_iat': True, | |
'verify_aud': True, | |
'verify_iss': True, | |
'require_exp': True, | |
'require_iat': True, | |
'require_nbf': False | |
} | |
) | |
logger.info("token is valid!") | |
logger.info("token payload is: \n {}".format(pformat(payload))) | |
except jwt.ExpiredSignatureError: | |
logger.info('expired token') | |
except jwt.InvalidSignatureError: | |
logger.info('invalid token signature') | |
except jwt.InvalidAudienceError: | |
logger.info('invalid audience') | |
except jwt.InvalidIssuerError: | |
logger.info('invalid issuer') | |
except jwt.DecodeError as e: | |
logger.info('invalid token, {}'.format(str(e))) | |
except ValueError as e: | |
logger.error(str(e), exc_info=True) | |
def load_key(key_path): | |
with open(key_path, 'r') as f: | |
return f.read() | |
if __name__ == '__main__': | |
logging.basicConfig(level=logging.INFO, | |
format="%(levelname)8s %(asctime)s %(message)s") | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-t', '--token', dest="token", | |
help="JWT token to decode") | |
parser.add_argument('-k', '--key-path', dest="key_path", | |
help="Path of public key file") | |
parser.add_argument('-a', '--aud', dest="audience", | |
help="Audience expected value") | |
parser.add_argument('-i', '--iss', dest="issuer", | |
help="Issuer expected value") | |
args = parser.parse_args() | |
decode_token( | |
token=args.token, | |
key=load_key(args.key_path), | |
audience=args.audience, | |
issuer=args.issuer | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment