Python
Prerequisites
To be able to decode JWT token with Python you need to install PyJWTpackage.
The best way to install it is through a pip package installer:
$ pip3 install pyjwtPyJWT usage
First, we need to import the PyJWT package:
import jwtSecond, we need to read and store a public key (used to decrypt a token). You need to get it from a dashboard beforehand and store somewhere near your project (./keys/id_rsa.pub).
# Choose a place to store a public key
pub_key_path = '.keys/id_rsa.pub'
with open(pub_key_path, mode='rb') as public_file:
PUBLIC_KEY = public_file.read()Now public key is stored in a variable PUBLIC_KEY.
Next, we need to implement a function to verify a token:
def verify_jwt(jwt_token):
try:
return jwt.decode(jwt_token, PUBLIC_KEY, algorithms='RS256')
except:
return NoneThis function contains two main branches: whether the token is valid or not.
After a try block there is an attempt to verify a token. If token is valid, then our verify_jwt function will return a JSON value of it. If token is incorrect or expired, verify_jwt returns None.
To use this function, you need to get pass it a JWT token.
jwt_token is a token you've received in a request. It is a string like that:
Result
If token is correct and did not expire, you'll receive a decoded JWT structure:
You can obtain challenge result in a result field.
Last updated
Was this helpful?