1

A correct working token causes a decoding error using pyjwt

  File "/usr/local/lib/python3.10/site-packages/jwt/api_jwt.py", line 129, in decode
    decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/jwt/api_jwt.py", line 100, in decode_complete
    decoded = api_jws.decode_complete(
  File "/usr/local/lib/python3.10/site-packages/jwt/api_jws.py", line 182, in decode_complete
    self._verify_signature(signing_input, header, signature, key, algorithms)
  File "/usr/local/lib/python3.10/site-packages/jwt/api_jws.py", line 269, in _verify_signature
    raise InvalidSignatureError("Signature verification failed")
jwt.exceptions.InvalidSignatureError: Signature verification failed

Method decode

code.py

    token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imdvb2dsZV9wYW5lbCIsInNjb3BlcyI6e30sImV4cGlyZV90aW1lIjoxNjY2ODA4NzYxLjE5OTIzNH0.ywGoByIbXA_9DGFzMUWF7fpu1P-Ab8lWOv8FiEhIczw'

class CustomAPI:    
    def _check_expire(self, token: str, key: str) -> str:
            try:
                jwt.decode(token, key, algorithms=['HS256'])
            except jwt.ExpiredSignatureError:
                token = self._get_authorize_token()
            return token
    
    
CustomAPI()._check_expire(token, settings.SECRET_KEY)

I saw a similar question and it suggested using b64decode for the key parameter

_check_expire(token, b64decode(settings.SECRET_KEY))

But the result is same

UPD

 key = 'h^z13$qr_s_wd65@gnj7a=xs7t05$w7q8!x_8zsld#'

I tried to use random string, but it didn't help

Jekson
  • 2,892
  • 8
  • 44
  • 79
  • There isn't much to do wrong in one call to jwt.decode. Can you share the secret, so that I could check it? Besides that, the "expire_time": 1666808761.199 looks odd, I doubt that jwt.decode even recognizes that. The corrrect claim is "exp" with a Unix timestamp in seconds. – jps Oct 26 '22 at 15:21
  • @jps I updated the question. About `expire_time` - I get it from a third party service, I can't affect it – Jekson Oct 26 '22 at 15:39
  • Hm, it looks like it's really about the token itself, not the key – Jekson Oct 26 '22 at 15:57
  • 1
    I checked it on jwt.io. This signature can't be verified with the given secret. Base64 decoding isn't an option, because it's not valid Base64. Nothing we can do here. But a remark regarding your expire_time: the `jwt.ExpiredSignatureError:` exception won't ever get raised. `jwt.decode()` will ignore the given expire_time, because it's a custom claim. You would need to write your own code for it. – jps Oct 26 '22 at 16:41

0 Answers0