Getting only decoded payload from JWT in python

半世苍凉 提交于 2021-01-18 20:31:44

问题


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.


回答1:


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

import jwt
key='super-secret'
payload={"id":"1","email":"myemail@gmail.com" }
token = jwt.encode(payload, key)
print (token)
decoded = jwt.decode(token, verify=False)  # works in PyJWT < v2.0
print (decoded)
print (decoded["email"])

For PyJWT v2.0 and above use:

decoded = jwt.decode(token, options={"verify_signature": False})

The old verify option was moved into the options dict

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

b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJlbWFpbCI6Im15ZW1haWxAZ21haWwuY29tIn0.ljEqGNGyR36s21NkSf3nv_II-Ed6fNv_xZL6EdbqPvw'

{'id': '1', 'email': 'myemail@gmail.com'}

myemail@gmail.com

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



来源:https://stackoverflow.com/questions/59425161/getting-only-decoded-payload-from-jwt-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!