41

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.

2
  • 1
    make your choice: jwt.io/#libraries-io Commented Dec 20, 2019 at 13:32
  • 4
    Man that's what i'm struggling with. All these libraries provide comprehensive approach. All that I want is to get easily a nice body of payload just like jwt.io allows me to do after pastying JWT into their tool. Commented Dec 20, 2019 at 14:18

3 Answers 3

104

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to have the header as well?
this is how it's done: jwt.get_unverified_header(token)
3

I used it today and seems like it needs the algorithm used too:

token = jwt.encode(payload, key=JWT_SECRET, algorithm="HS512")

jwt.decode(token, algorithms='HS512', verify=True, key=JWT_SECRET)
{'id': '1', 'email': '[email protected]'}

Comments

1

the accepted answer is a bit outdated now. As of this writing jwt==1.3.1 and there are slight changes to the library. You should do

from jwt import JWT
instance=JWT()
token="my.token.secret"
instance.decode(token, do_verify=False)  # only if you do not want to perform a verification

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.