How to verify a JWT using python PyJWT with a public PEM cert?

I am using python 3.6

import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
key = b"""-----BEGIN PUBLIC KEY-----
MIIBI....<<Your public key basically>>
-----END PUBLIC KEY-----"""
public_key = serialization.load_pem_public_key(key, backend=default_backend())
print(jwt.decode(token, public_key))

This worked like a charm for me.


If the key file is generated using ssh-keygen -t rsa (RFC4716), you can use the file directly.

Encode:

import jwt

pemfile = open("id_rsa", 'r')
keystring = pemfile.read()
pemfile.close()
token = jwt.encode(payload, keystring, algorithm='RS256')

Decode:

import jwt

pemfile = open("id_rsa.pub", 'r')
keystring = pemfile.read()
pemfile.close()
payload = jwt.decode(toekn, keystring,  verify=True)

dont forget to catch errors like jwt.ExpiredSignatureError etc


You need to pass the public key instead of the full certificate to the decode method. So extract the key from the certificate in order to use it as in:

from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

cert_str = "-----BEGIN CERTIFICATE-----MIIDETCCAfm..."
cert_obj = load_pem_x509_certificate(cert_str, default_backend())
public_key = cert_obj.public_key()

and then:

token_string = "eyJhbGciOiJSUzI1NiIsImtpZCI6I..."
jwt.decode(token_string, public_key, algorithms=['RS256'])

Tags:

Python

Rsa

Pem

Jwt