我应该如何处理@jwt_required decorator中引发的异常?(在扩展了jwt的烧瓶中)



我有一个带有@jwt_required decorator的函数。

class Test(Resource):
@jwt_required
def get(self):
return {"test": "ok" }

当设置了正确的HTTP标头(即)时,它可以正常工作

Authentication: Bearer [TOKEN]

但当令牌无效/错误或混乱时,会引发jwt.exceptions.DecodeError:

File "env/lib/python3.6/site-packages/flask_restplus/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 103, in wrapper
verify_jwt_in_request()
File "env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 32, in verify_jwt_in_request
jwt_data = _decode_jwt_from_request(request_type='access')
File "env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 267, in _decode_jwt_from_request
decoded_token = decode_token(encoded_token, csrf_token)
File "env/lib/python3.6/site-packages/flask_jwt_extended/utils.py", line 80, in decode_token
encoded_token, verify=False, algorithms=config.algorithm
File "env/lib/python3.6/site-packages/jwt/api_jwt.py", line 84, in decode
payload, _, _, _ = self._load(jwt)
File "env/lib/python3.6/site-packages/jwt/api_jws.py", line 183, in _load
raise DecodeError('Not enough segments')
jwt.exceptions.DecodeError: Not enough segments

我不能依赖客户端总是使用正确的令牌。我无法捕获异常,因为它是在decorator中引发的,而不是我自己的函数。因此,结果是http 500错误。我应该如何更优雅地处理异常?

Flask jwt extended应该能优雅地为您处理这些问题。如果没有,您可能正在使用另一个扩展(例如flask restful),它正在破坏本地flask的功能。您可以尝试设置此选项以修复app.config[‘PROPAGATE_EXCEPTIONS’] = True,或者如果您使用的是导致问题的其他烧瓶扩展,请查看此线程以获得一些建议https://github.com/vimalloc/flask-jwt-extended/issues/86

相关内容

  • 没有找到相关文章

最新更新