Decoding JWT with Python

A Step-by-Step Guide

Mansoor Aldosari
2 min readSep 30, 2023
Photo by Patrick Robert Doyle on Unsplash

JSON Web Tokens (JWTs) have become a popular method for securely transmitting information between parties. They are often used for user authentication, authorization, and data integrity verification. In this blog post, we’ll walk you through the process of decoding JWTs using Python. By the end of this guide, you’ll be able to understand the structure of JWTs and how to extract meaningful information from them.

Before we dive into decoding JWTs, let’s briefly understand what JWTs are. A JWT is a compact, self-contained token format that can represent claims between two parties. These claims are typically used to identify a user or provide some information about them. JWTs consist of three parts: a header, a payload, and a signature.

  1. Header: The header typically consists of two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.
  2. Payload: The payload contains claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
  3. Signature: To create the signature part you have to take the encoded header, the encoded payload, a secret, and the algorithm specified in the header, and sign that.

Now, let’s write a Python script to decode a JWT. For this example, we’ll assume you have a JWT and a secret key (if applicable). Replace YOUR_JWT_HERE and YOUR_SECRET_HERE with your actual JWT and secret key.

import jwt

# Replace with your JWT and secret key
jwt_token = "YOUR_JWT_HERE"
secret_key = "YOUR_SECRET_HERE"

try:
# Decode the JWT
decoded_payload = jwt.decode(jwt_token, secret_key, algorithms=["HS256"])

# Print the decoded payload
print(decoded_payload)
except jwt.ExpiredSignatureError:
print("JWT has expired.")
except jwt.InvalidTokenError:
print("Invalid JWT")

The decoded payload will be a dictionary containing the claims from the JWT. You can access individual claims by their keys. Common claims include iss (issuer), sub (subject), exp (expiration time), and iat (issued at). The specific claims in your JWT will depend on its purpose.

In this guide, we’ve walked through the process of decoding JWTs using Python and the PyJWT library. Understanding the structure of JWTs and how to decode them is essential when working with authentication and authorization in web applications. With this knowledge, you can extract valuable information from JWTs and use it to make informed decisions in your applications.

--

--