简体   繁体   English

我应该如何处理@jwt_required装饰器中引发的异常? (在flask-jwt-extended中)

[英]How should I handle exceptions raised in @jwt_required decorator? (in flask-jwt-extended)

I have a function with @jwt_required decorator. 我有一个@jwt_required装饰器的函数。

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

Which works fine when the correct HTTP header is set, ie 设置正确的HTTP标头后,即可以正常工作

Authentication: Bearer [TOKEN]

but when the token is invalid/wrong or messed with, a jwt.exceptions.DecodeError is raised: 但是当令牌无效/错误或混乱时,将引发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

I cannot rely on clients always using correct tokens all the time. 我不能一直依赖客户机始终使用正确的令牌。 And I cannot catch the exception because it is raised in the decorator rather than my own function. 而且我无法捕获异常,因为它是在装饰器中而不是我自己的函数中引发的。 So the result is a http 500 error. 因此结果是http 500错误。 How should I handle the exception more gracefully? 我应该如何更优雅地处理异常?

Flask-jwt-extended should be handling those for you gracefully. Flask-jwt-extended应该可以为您优雅地处理它们。 If not, you are probably using another extension (like flask-restful for example) that is breaking native flask functionality. 如果没有,您可能正在使用另一个扩展(例如,flask-restful)破坏了本地flask的功能。 You can try setting this option to fix it app.config['PROPAGATE_EXCEPTIONS'] = True , or take a look at this thread for some advice if you are using a different flask extension that is causing problems https://github.com/vimalloc/flask-jwt-extended/issues/86 您可以尝试设置此选项来修复它app.config['PROPAGATE_EXCEPTIONS'] = True ,如果您使用的是引起问题的https://github.com/ vimalloc /烧瓶-JWT扩展/问题/ 86

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM