Search code examples
jwtdecodejjwtpyjwt

Convert JWT token created by Java JWT in python


I have received a JWT token created by a java program using jjwt module. Now, when I try to verify the token using pyjwt, it throws exception.

import jwt token
token='eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMDAiLCJyb2xlcyI6IkJVU0lORVNTVVNFUiIsIm1vZGUiOiJzdG9yZWFwcCIsImlhdCI6MTQ5NDg1ODk4MCwiZXhwIjoxNDk0ODY0OTgwfQ.ckFnGv1NT-Ui2S90DNr50YoHSXc1ZLBNnEErnGMWL-E'
secret ='123456AB' 
jwt.decode(token,secret,algorithms='HS256')

Traceback (most recent call last): File "", line 1, in File "/Applications/anaconda/envs/modulename/lib/python3.5/site-packages/jwt/api_jwt.py", line 64, in decode options, **kwargs) File "/Applications/anaconda/envs/modulename/lib/python3.5/site-packages/jwt/api_jws.py", line 116, in decode key, algorithms) File "/Applications/anaconda/envs/modulename/lib/python3.5/site-packages/jwt/api_jws.py", line 186, in _verify_signature raise DecodeError('Signature verification failed') jwt.exceptions.DecodeError: Signature verification failed

If i use the same token in jwt.io, with base64 encrypted option checked, it seems to work.


Solution

  • This is because when Java created the token it thought the plain text you used as a secret was base64 encoded. I am assuming Java was expecting the string secret to be base64 encoded version of some binary. Try base64 decoding the secret before decoding jwt.

    import base64
    jwt.decode(token,base64.b64decode(secret))
    
    #The token in your question was expired so I ended up passing verify expiration = False
    jwt.decode(token,base64.b64decode(secret), options={ 'verify_exp': False})
    
    {u'iat': 1494858980, u'exp': 1494864980, u'sub': u'100', u'roles': u'BUSINESSUSER', u'mode': u'storeapp'}