Handling JWT in Python

JSON Web Tokens (JWT) is an open standard (RFC 7519 ) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

JWT Structure

JWTs consist of three parts separated by dots:

  • Header
  • Payload
  • Signature

The header contains the algorithm used to sign the token and the type of token. The header is base64 encoded and looks like this:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

Contains a set of claims.

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Signature

The signature is used to verify the integrity of the token. It is created by signing the header and payload with a secret key. The signature is base64 encoded and looks like this:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret
)

JWT in Python

In Python, we can use pyjwt . Another option is python-jose but it seems not actively maintained.

$ pip install pyjwt[crypto]

Note that it’s better to include the [crypto] to install the cryptography module for working with RSA .

Decode JWT Token

>>> decoded = jwt.decode(encoded, public_key, algorithms=["RS256"])
{'some': 'payload'}

Sometimes, we may just want to decode the key without validation of the signature by setting the verify_signature option to False.

>>> jwt.decode(encoded, options={"verify_signature": False})
{'some': 'payload'}

Similarly, we can read the headers without validation:

>>> jwt.get_unverified_header(encoded)
{'alg': 'RS256', 'typ': 'JWT', 'kid': 'key-id-12345...'}

For more examples, see here from pyjwt documentation.