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 pyjwt

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 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 None

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:

>>> jwt_token
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJjaGFsbGVuZ2VfaWQiOiI2MTAyZTBlNi1hMDZjLTRmODEtYjA5NS03ZGUxODUzY2U1YTIiLCJyZXN1bHQiOjAuOTQ5NDQ3NTU2MDI4NzU2LCJpYXQiOjE1NzgzMzY1NzMsImV4cCI6MTU3ODMzNjYzM30.UGFLV4qJGWEF2ZDpFk5tafBB9q9DwHOEMw9i7y_gQ6GsgyD5C9osoXaQwlZXaQ_oDoeGDGiLUzjFdsdhDAADEAGKbmuiLC1JWWdd-pC2JxIQlId4kLw1hZEe6ljUljxSJH980rWoeUMhNjmq3CddaesoYBxi1hLW0LM0oWv_DxNZqzd8VehM1rS8hDRszgG-EJR_lWr3sMMyN82mh4-55xEgNd3KF_UG0hqja55x6pESTEhmTxzAjywK5tiitwOYoRgy2W_krOD6oUadJlX_0W4CLzn2g0gdjwtYxNfImdcJoIXSSWoMC1NikSMIsrDmGtofjS_icmwn_cxks-Qyhg"

Result

If token is correct and did not expire, you'll receive a decoded JWT structure:

{
  "challenge_id": "3aa67786-d8cb-4ed5-ae83-ae7ace27e372",
  "result": 0.949447556028756,
  "iat": 1578001068,
  "exp": 1578001128
}

You can obtain challenge result in a result field.

Last updated