Token validation with python

I’ve managed some minor success using pyjwt, though there must still be an easier way to do this. The certificate in /.well-known/jwks.json is x.509. pyjwt requires the public key, so you need to extract that from the cert. This can probably be done without “reconstituting” the cert as I have done, but it works. cert is the x.509 certificate string from jwks.json:

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

def extract_public_key(cert):
    cert_string = textwrap.wrap(cert, width=64)
    cert = '-----BEGIN CERTIFICATE-----\n'
    for line in cert_string:
        cert += line + '\n'
    cert += '-----END CERTIFICATE-----\n'
    cert_obj = load_pem_x509_certificate(cert.encode(), default_backend())
    return cert_obj.public_key()

Then I validate the audience. env holds config parameters like the client ID, audience:

import jwt

def validate_token(token, jwks, env):
    public_key = extract_public_key()jwks['x5c'][0]
    return jwt.decode(token['access_token'], public_key, audience=env['audience'], algorithms=['RS256'])

The above should be wrapped in a try: clause, catching jwt.InvalidAudienceError.

I may go back and give python-jose or authlib another shot.

Unrelated aside: for some reason, when I try to import pyjwt, authlib, or python-jose, pylint in VS Code tells me it cannot load any of those modules. But the script runs fine. ¯\_(ツ)_/¯