'How to extract jwt token payload when token is expired in python jwt
I am unable to extract JWT token payload after the jwt token expires in python jwt package. I am using flask api for backend development and the implementation is in the middleware.
Below is my code:
import jwt
from flask import request
from functools import wraps
from werkzeug.exceptions import Forbidden, Unauthorized
def admin_rights_required(f):
@wraps(f)
def _decorated(*args, **kwargs):
config = readConfig()
secretKey = config["JWT_SECRET_KEY"]
algorithm = config["JWT_ENCODING_ALGORITHM"]
token = None
if "Authorization" in request.headers:
data = request.headers["Authorization"]
token = str.replace(str(data), "Bearer ", "")
try:
if not token or (not _ruleUserObj.getRuleUserFromToken(token)):
data = jwt.decode(token, secretKey, algorithms=algorithm)
raise Unauthorized("Token is missing")
data = jwt.decode(token, secretKey, algorithms=algorithm)
if getTokenDurationDifference(token) == -1:
raise jwt.InvalidTokenError
currentUser = _ruleUserObj.getRuleUser(data["sub"]["username"])
if not len(currentUser) > 0:
raise jwt.InvalidTokenError
if currentUser["isAdmin"] == False:
raise Forbidden()
except jwt.ExpiredSignatureError:
_ruleUserObj.updatedRuleUserSessionRemToken(data["sub"]["username"])
raise Unauthorized("Signature expired. Please log in again.")
except jwt.InvalidTokenError:
_ruleUserObj.updatedRuleUserSessionRemToken(data["sub"]["username"])
raise Unauthorized("Invalid token. Please log in again.")
return f(*args, **kwargs)
return _decorated
Solution 1:[1]
I have found out the solution in the jwt package in python. Below is the link for reference:
https://pyjwt.readthedocs.io/en/latest/usage.html#reading-the-claimset-without-validation
Below is the code change which I did for the above:
jwt.decode(
token,
secretKey,
algorithms=algorithm,
options={"verify_signature": False},
)
)["sub"]["username"]
)
After merging the code with the main code it looks like below:
import jwt
from flask import request
from functools import wraps
from werkzeug.exceptions import Forbidden, Unauthorized
def admin_rights_required(f):
@wraps(f)
def _decorated(*args, **kwargs):
config = readConfig()
secretKey = config["JWT_SECRET_KEY"]
algorithm = config["JWT_ENCODING_ALGORITHM"]
token = None
if "Authorization" in request.headers:
data = request.headers["Authorization"]
token = str.replace(str(data), "Bearer ", "")
try:
if not token or (not _ruleUserObj.getRuleUserFromToken(token)):
data = jwt.decode(token, secretKey, algorithms=algorithm)
raise Unauthorized("Token is missing")
data = jwt.decode(token, secretKey, algorithms=algorithm)
if getTokenDurationDifference(token) == -1:
raise jwt.InvalidTokenError
currentUser = _ruleUserObj.getRuleUser(data["sub"]["username"])
if not len(currentUser) > 0:
raise jwt.InvalidTokenError
if currentUser["isAdmin"] == False:
raise Forbidden()
except jwt.ExpiredSignatureError:
_ruleUserObj.updatedRuleUserSessionRemToken(
(
jwt.decode(
token,
secretKey,
algorithms=algorithm,
options={"verify_signature": False},
)
)["sub"]["username"]
)
raise Unauthorized("Signature expired. Please log in again.")
except jwt.InvalidTokenError:
_ruleUserObj.updatedRuleUserSessionRemToken(
(
jwt.decode(
token,
secretKey,
algorithms=algorithm,
options={"verify_signature": False},
)
)["sub"]["username"]
)
raise Unauthorized("Invalid token. Please log in again.")
return f(*args, **kwargs)
return _decorated
There is alternative way to decode the jwt token if it is expired: As suggested by @KlausD. Below is the implementation:
import base64
import json
tokenSplit = token.split(".")
json.loads((base64.b64decode(tokenSplit[1])).decode("utf-8"))
Thanks to @KlausD. for the simple hack
Solution 2:[2]
If the options parameter doesn't work like this: options = { "verify_signature": False }
Using the lib pyjwt==1.7.1 try to inform the parameter "verify=False", like this here:
payload = jwt.decode(jwt=token, key=secret, verify=False, algorithms = [ 'HS256' ])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Fabiano Souza |