decode jwt token in python

本文解决jwt token 在 python中decode报错的问题,至于JWT是什么,见 jwt.io

decode jwt token in python

根据 jwt.io 介绍 jwt token 由三部分构成,前两部分由base64UrlEncode编码构成

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
your-256-bit-secret
) 

但是,在python中使用base64.urlsafe_b64decode()由的时候会以下错误

import base64
s = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
"
base64.urlsafe_b64decode(s.split(".")[1])
---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
 in ()
----> 1 base64.urlsafe_b64decode(s.split(".")[1])

c:\users\lenovo\appdata\local\programs\python\python36\lib\base64.py in urlsafe_b64decode(s)
    131     s = _bytes_from_decode_data(s)
    132     s = s.translate(_urlsafe_decode_translation)
--> 133     return b64decode(s)
    134
    135

c:\users\lenovo\appdata\local\programs\python\python36\lib\base64.py in b64decode(s, altchars, validate)
     85     if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
     86         raise binascii.Error('Non-base64 digit found')
---> 87     return binascii.a2b_base64(s)
     88
     89

Error: Incorrect padding

这个是因为base64UrlEncode 会把base64后面产生的=号给去掉,造成token中第二段有的时候补全的=消失,所以在decode的时候要把64位token=补全

In [22]: base64.urlsafe_b64decode(s.split(".")[1] + '=' * (4 - len(s.split(".")[1]) % 4))
Out[22]: b'{"user_id":"5b7cfbd45f627ddd88e2c929","exp":1535096912}'

见 https://stackoverflow.com

你可能感兴趣的:(decode jwt token in python)