JWT Python implementation
2 min readJan 26, 2024
In this article, I will explain on how to implement Json Web Token(JWT) in python. You can refer this link on how JWT internally works.
I have created simple REST API application in python which serves two end points as below
1. /login this request will generate JWT token, attaches to the response.(Hard coded users details in the source for ease)
2. /products this will give product details if the token is valid.
JWT token creation code snippet in python:
if input_data.get("password") == password:
# jwt paylaod
payload = {
"user_name": input_data.get("user_name"),
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=5),
}
# creating JWT token with expiry of 5 mins
token = jwt.encode(payload, SECRET_KEY)
# Appending token in the login success response
return {
"data": {"user_name": input_data.get("user_name"), "token": token},
"message": "User login successfully",
}, 200
JWT token validation code snippet in python
token = None
if "Authorization" in request.headers:
token = request.headers["Authorization"].split(" ")[1]
if not token:
return make_error_response("Authentication Token is missing!", 400)
try:
# decoding jwt token with secret
data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
# verifying whether token is belogns to current user
current_user = static_users.get(data["user_name"])
if current_user is None:
return make_error_response("Invalid Authentication token!", 401)
# Convert the expiration time to a datetime object
expiration_datetime = dt.utcfromtimestamp(data["exp"])
# Get the current time
current_time = dt.utcnow()
# Check if the token has expired
if current_time > expiration_datetime:
return make_error_response("Token has expired", 401)
# token is valid, process the request
except jwt.ExpiredSignatureError:
return make_error_response("Token has expired", 401)
except jwt.InvalidTokenError:
return make_error_response("Token is invalid", 401)
Python Packages required for JWT generation:
- PyJWT: to encode and decode JWT token
- Flask: To run application server(You can use FastAPI or any similar python package for application server.)
Refer GitHub for complete source code.