在python中仅从JWT获取已解码的有效负载 [英] Getting only decoded payload from JWT in python

查看:178
本文介绍了在python中仅从JWT获取已解码的有效负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种很好的方法(可能使用一些库)来仅将JWT的有效载荷保存为字符串变量? 除了手动解析第一点和第二点之间的内容然后解码.

解决方案

PyJWT 可以选择 import jwt key='super-secret' payload={"id":"1","email":"myemail@gmail.com" } 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"])

对于PyJWT< v2.0使用:

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

它返回一个字典,以便您可以单独访问每个值:

b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJlbWFpbCI6Im15ZW1haWxAZ21haWwuY29tIn0.ljEqGNGyR36s21NkSf3Zv_6'

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

myemail@gmail.com

注意:还有其他适用于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.

解决方案

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":"myemail@gmail.com" }
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': '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.

这篇关于在python中仅从JWT获取已解码的有效负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆