Search code examples
pythonjwtjwk

How to decode JWT token with JWK in Python


I am developing an application where all the API's are protected by OAuth. I have received the access token from the client, but could not decode and validate the token.

I have JWK in the below format

{
  "keys": [
    {
      "kty": "RSA",
      "x5t#S256": "Some value",
      "e": "Some Value",
      "x5t": "Some Value",
      "kid": "SIGNING_KEY",
      "x5c": [
        "Some Value"
      ],
      "key_ops": [
        "verify",
        "encrypt"
      ],
      "alg": "RS256",
      "n": "Some Value"
    }
  ]
}

How to decode the JWT token using above JWK in Python?


Solution

  • Fast check of your jwt token https://jwt.io/

    otherwise you can try this, but you should know the algorithm used to generate the token (e.g. : HS256) and the key used for signing the token) (e.g. :super_secretkey)

    
    import jwt # pip install pyjwt[crypto] to install the package
    jwt.decode(token, key='super_secretkey', algorithms=['HS256', ])
    

    Update decode the JWT using JWK

    import json
    import jwt
    
    #for JWKS that contain multiple JWK
    public_keys = {}
    for jwk in jwks['keys']:
        kid = jwk['kid']
        public_keys[kid] = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))
    
    kid = jwt.get_unverified_header(token)['kid']
    key = public_keys[kid]
    
    payload = jwt.decode(token, key=key, algorithms=['RS256'])