Getting Started with JSON Web Tokens and Python

JSON Web Token is an open standard that defines a way for securely transmitting JSON objects. The JSON object can be verified and trusted because it’s digitally signed. The JSON web tokens can be signed by using a secret with the HMAC algorithm or by public / private key pair using RSA.

When to use JWT

There are two major use cases where JWTs are useful: authentication and information exchange.

Full details of how JSON Web Tokens work can be found on Introduction to JSON Web Tokens site.

Python and JSON Web Tokens

The very basic usage of JWT with Python is illustrated below.

Start Python REPL and import jwt package. Note that pyjwt need to be installed first.

Step 1 – Import jwt

Python 3.6.4 (default, Mar  5 2018, 20:26:38)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
>>> import jwt

Step 2 – Create a token

>>> token = jwt.encode({'key': 'value'}, 'my-secret', algorithm='HS256')
>>> token
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSJ9.fYJR-2DQIf30n5imBRciRuE9P5xkUc0HurChBDtAWnU'

Step 3 – Decode the token

>>> jwt.decode(token, 'my-secret', algorithms=['HS256'])
{'key': 'value'}

The token created in step 2 does not have expiration date. In order to create more secure token that expire after a given number of seconds we would create it in the following way:

Step 1 – Create a token that will expire after 30 seconds from now:

>>> import datetime
>>> token = jwt.encode({'key': 'value', 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=30)}, 'my-secret', algorithm='HS256')
>>> token
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSIsImV4cCI6MTUyMDU4MzIyNX0.Ews5xpbp9duohIJSCVSR_iihxrtFPqjcsKM-IC1nnJk'

Step 2 – Decode token within the expiration time:

>>> jwt.decode(token, 'my-secret', algorithms=['HS256'])
{'key': 'value', 'exp': 1520583225}

Step 3 – Decode token after the 30 seconds time window:

>>> jwt.decode(token, 'my-secret', algorithms=['HS256'])
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/jakub/projects/fitlog/venv/lib/python3.6/site-packages/jwt/api_jwt.py", line 89, in decode
    self._validate_claims(payload, merged_options, **kwargs)
  File "/Users/jakub/projects/fitlog/venv/lib/python3.6/site-packages/jwt/api_jwt.py", line 119, in _validate_claims
    self._validate_exp(payload, now, leeway)
  File "/Users/jakub/projects/fitlog/venv/lib/python3.6/site-packages/jwt/api_jwt.py", line 160, in _validate_exp
    raise ExpiredSignatureError('Signature has expired')
jwt.exceptions.ExpiredSignatureError: Signature has expired

The most common use case for tokens with expiration date is password reset functionality. Many other examples of how to use JWT and Python can be found on this site.