PyJWT 中无效 JWT 的基本异常是什么?

问题描述 投票:0回答:2

根据 PyJWT 的文档,类 jwt.exceptions.InvalidTokenError 是解码方法失败时的基本错误。但是,以下代码仍然会因不同的异常而中断:

try:
  jwt.decode(jwt_token, os.environ['SECRET'], algorithms="HS256")
except jwt.exceptions.InvalidTokenError:
  pass

我的想法是,由于 InvalidTokenError 是基本错误,因此此 except 块应该捕获所有其他可能的 PyJWT 错误,例如 InvalidSignatureError、DecodeError 等。我的问题是我可以使用 PyJwt 是否存在基本错误。我知道使用

except Exception
始终是一种选择,但这是不好的形式,所以我想如果可能的话避免它。谢谢!

python jwt pyjwt
2个回答
1
投票

我让这个微观示例发挥作用。一般来说,不要传递异常,至少打印错误消息。

#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))

输出:

{'sub': '1234567890', 'name': 'John Doe', 'iat': 1516239022}

提出了哪个错误?我最好的猜测是你还有另一个问题。 Secret 的 KeyError,不是与 jwt 相关的错误:

WARNING NORMAL EXCEPTION CAUGHT
KeyError('SECRET')

如果您的令牌不正确,您会得到以下信息:

DecodeError('Not enough segments')

如果您的签名不正确,则:

InvalidSignatureError('Signature verification failed')

0
投票

阅读

中的代码

[https://github.com/jpadilla/pyjwt/blob/master/jwt/exceptions.py][1]

仅识别我使用的 jwt 错误

jwt.exceptions.PyJWTError

所以:

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)
 except Exception as e:
   logging.error(e)
© www.soinside.com 2019 - 2024. All rights reserved.