Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only decoded payload from JWT in python

Tags:

python

jwt

Is there a nice way (using maybe some library) to get only payload from JWT saved as string variable? Other than manually parsing it for content between first and second dots and then decoding.

like image 867
salveiro Avatar asked Dec 20 '19 12:12

salveiro


People also ask

How do I get data from JWT token in Python?

The library PyJWT has an option to decode a JWT without verification: Without this option, the decode function does not only decode the token but also verifies the signature and you would have to provide the matching key. And that's of course the recommended way.

How do I get my JWT payload?

Each JWT contains a payload. The payload is a base64 encoded JSON object that sits between the two periods in the token. We can decode this payload by using atob() to decode the payload to a JSON string and use JSON. parse() to parse the string into an object.

How do you decode a token in Python?

Key Changes x for decoding Azure AD Access Tokens with Python is to use the get_unverified_header function to retrieve the algorithm of the access token then use the decode function to decode it. The decode function requires the algorithms option to specify the encoding.

How do I verify JWT without secret?

There are two ways in which a public/private keys can be used by a JWT: signing and encryption. If you use a private key for signing, it allows for the recipient to identify the sender of the JWT and the integrity of the message but not to hide its contents from others (confidentiality).


1 Answers

The library PyJWT has an option to decode a JWT without verification:

Without this option, the decode function does not only decode the token but also verifies the signature and you would have to provide the matching key. And that's of course the recommended way.
But if you, for whatever reason, just want to decode the payload, set the option verify_signatureto false.

import jwt
key='super-secret'
payload={"id":"1","email":"[email protected]" }
token = jwt.encode(payload, key)
print (token)
decoded = jwt.decode(token, options={"verify_signature": False}) # works in PyJWT >= v2.0
print (decoded)
print (decoded["email"])

For PyJWT < v2.0 use:

decoded = jwt.decode(token, verify=False)  # works in PyJWT < v2.0

It returns a dictionary so that you can access every value individually:

b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJlbWFpbCI6Im15ZW1haWxAZ21haWwuY29tIn0.ljEqGNGyR36s21NkSf3nv_II-Ed6fNv_xZL6EdbqPvw'

{'id': '1', 'email': '[email protected]'}

[email protected]

Note: there are other JWT libs for python as well and this might also be possible with other libs.

like image 141
jps Avatar answered Sep 16 '22 13:09

jps