![]() |
https://www.pexels.com/photo/close-up-of-keys-333837/ |
Given a JWT that is issued by Microsoft's Identity Service, we want to validate it with
pyJWT
.In this blog, we share how to get the public key and how to validate the JWT.
First, we need a copy of the JWT, we can use browser's debugger to fish it out. Since this is a bearer token, we have to be careful with it (do not share it).
Next, we can decode it at https://jwt.ms. There are two things that we are hoping to get
- the
kid
, Key Identifier. - the issuer,
iss
the iss has a value like
https://<id>.ciamlogin.com/<id>/v2.0
. We alter the URL to this https://<id>.ciamlogin.com/<id>/discovery/v2.0/keys
. Adding discovery
and keys
accordingly.Then, we point our browser to https://<id>.ciamlogin.com/<id>/discovery/v2.0/keys
. And we will get something like this.
kid
in the JWT. Copy the dictionary and paste it into jwk
variable.import json import jwt from cryptography.hazmat.primitives import serialization jwk = <here> public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk)) pubk_bytes = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) print(pubk_bytes.decode("utf-8"))
Note: remember to pip install jwt[crypto]
This will print the public key in PEM format. This string can be set in environment parameter and use for verify JWT like this.
payload = jwt.decode( token.credentials, audience=<audience> algorithms=[<algorithm>], # e.g. RS256 key=<public_key>, options={"verify_signature": True}, )
Comments
Post a Comment