Reputation: 412
According to the documentation for PyJWT, the class jwt.exceptions.InvalidTokenError is the base error when the decode method fails. However, the following code still breaks with different exceptions:
try:
jwt.decode(jwt_token, os.environ['SECRET'], algorithms="HS256")
except jwt.exceptions.InvalidTokenError:
pass
My thinking was that since InvalidTokenError is the base error, this except block should catch all the other possible PyJWT errors such as InvalidSignatureError, DecodeError etc. My question is if there is a base error for PyJwt I could use. I know using except Exception
is always an option but that's bad form so I'd like to avoid it if possible. Thanks!
Upvotes: 2
Views: 4913
Reputation: 51
Reading the code in
https://github.com/jpadilla/pyjwt/blob/master/jwt/exceptions.py
for identify only jwt errors I use
jwt.exceptions.PyJWTError
so:
try:
logging.info("Decode token jwt")
token_decoded = jwt.decode(payload["token"], key=JWT_KEY, algorithms=['HS256'])
...
except jwt.exceptions.PyJWTError as e:
logging.error(e)
#all jwt error
except Exception as e:
logging.error(e)
#all other errors
Upvotes: 0
Reputation: 1087
I got this micro example working. In general, don't pass an exception, at least print the error message.
#pip install pyjwt
import os, jwt, hashlib
jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.VUI28NztICBIB9m6kZolIEzYJojrw0eUr_4bVoQ1Ong"
os.environ['SECRET'] = hashlib.sha256(b"0").hexdigest()
try:
print(jwt.decode(jwt_token, os.environ['SECRET'], algorithms="HS256"))
except jwt.exceptions.InvalidTokenError as e:
print(repr(e))
except Exception as e:
print("WARNING NORMAL EXCEPTION CAUGHT")
print(repr(e))
Output:
{'sub': '1234567890', 'name': 'John Doe', 'iat': 1516239022}
Which error was raised? My best guess is that you have another problem. KeyError for Secret, is not an error related to jwt:
WARNING NORMAL EXCEPTION CAUGHT
KeyError('SECRET')
If your token is incorrect, you get this:
DecodeError('Not enough segments')
And if your signare is not correct, this:
InvalidSignatureError('Signature verification failed')
Upvotes: 2