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:
$pip3installpyjwt
PyJWT usage
First, we need to import the PyJWT package:
import jwt
Second, 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 keypub_key_path ='.keys/id_rsa.pub'withopen(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:
This 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.
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCvt9ZrQP23A06ZLaOLoXtY2NYLkaAO+UyJG7S6WPD4ue49flkzNEKYlTKdk3L9HzMNeQZTqT+Bn310E/u/yOci8yY8GUBNb+kuH1VM2EAl7MPY41eX+tZe/wy0OWvrnhj1H5V5aXt8hISbIZLmgtUQWNINn/xsrn8EIETxbHiEVAXZoVXQYddiw+EY6uD/GRPCLNVr4gx43Yfcx+jSACotoy2hmK8v6N5VmLs+AOILf4INfE8MnzAJt8PD5T5CEVPO82+qj67E9Y40tQnyWpZ028QOerFnqRNRoa0+Fh5xXE+lExP8gRq47cUmWLAkCpUpNvFyStkr56SWrE/NZgCx"
result =verify_jwt(jwt_token)
jwt_token is a token you've received in a request. It is a string like that: