Flask 学习-92.使用 gunicorn 部署 flask 出现NoAuthorizationError: Missing JWT in headers or cookies问题

冯新知
2023-12-01

前言

我在使用 gunicorn 部署 flask线上环境,访问需要jwt auth的接口地址,不断收到" NoAuthorizationError Missing Authoring Header"错误

问题描述

环境描述:
1.python3.8
2.flask 2.0.2
3.Flask-JWT-Extended==4.4.4

python3.8 的版本,在本地使用flask run启动访问没任何问题,访问一个需要jwt auth的接口, 正常返回401 UNAUTHORIZED

HTTP/1.0 401 UNAUTHORIZED
Content-Type: application/json
Content-Length: 44
Server: Werkzeug/2.0.2 Python/3.8.5
Date: Sat, 15 Oct 2022 14:28:01 GMT

{
  "err": "Missing Authorization Header"
}

在线上服务器用gunicorn 部署 flask,使用gunicorn 启动服务

gunicorn -w 2 -b 0.0.0.0:8001 app:app

具体部署方式,参考前面这篇https://www.cnblogs.com/yoyoketang/p/16794906.html

出现问题,当我访问一个需要@jwt_required() token认证接口


运行日志

2022-10-15 13:40:14,606 - apis - ERROR - Exception on /api/project [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/api.py", line 403, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask/views.py", line 84, in view
    return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/resource.py", line 49, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/marshalling.py", line 248, in wrapper
    resp = f(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 153, in decorator
    verify_jwt_in_request(optional, fresh, refresh, locations, verify_type)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 89, in verify_jwt_in_request
    jwt_data, jwt_header, jwt_location = _decode_jwt_from_request(
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 323, in _decode_jwt_from_request
    decoded_token = decode_token(encoded_token, csrf_token)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/utils.py", line 127, in decode_token
    return jwt_manager._decode_jwt_from_config(encoded_token, csrf_value, allow_expired)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/jwt_manager.py", line 553, in _decode_jwt_from_config
    return _decode_jwt(**kwargs, allow_expired=allow_expired)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/tokens.py", line 94, in _decode_jwt
    decoded_token = jwt.decode(
  File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 129, in decode
    decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/jwt/api_jwt.py", line 100, in decode_complete
    decoded = api_jws.decode_complete(
  File "/usr/local/lib/python3.8/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.8/site-packages/jwt/api_jws.py", line 269, in _verify_signature
    raise InvalidSignatureError("Signature verification failed")
jwt.exceptions.InvalidSignatureError: Signature verification failed
2022-10-15 13:42:10,360 - apis - ERROR - Exception on /api/project [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/api.py", line 403, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask/views.py", line 84, in view
    return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/resource.py", line 49, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/marshalling.py", line 248, in wrapper
    resp = f(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 153, in decorator
    verify_jwt_in_request(optional, fresh, refresh, locations, verify_type)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 89, in verify_jwt_in_request
    jwt_data, jwt_header, jwt_location = _decode_jwt_from_request(
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 339, in _decode_jwt_from_request
    raise NoAuthorizationError(err_msg)
flask_jwt_extended.exceptions.NoAuthorizationError: Missing JWT in headers or cookies (Missing Authorization Header; Missing cookie "access_token_cookie")
2022-10-15 13:45:46,960 - apis - ERROR - Exception on /api/project [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/api.py", line 403, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask/views.py", line 84, in view
    return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/resource.py", line 49, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_restx/marshalling.py", line 248, in wrapper
    resp = f(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 153, in decorator
    verify_jwt_in_request(optional, fresh, refresh, locations, verify_type)
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 89, in verify_jwt_in_request
    jwt_data, jwt_header, jwt_location = _decode_jwt_from_request(
  File "/usr/local/lib/python3.8/site-packages/flask_jwt_extended/view_decorators.py", line 339, in _decode_jwt_from_request
    raise NoAuthorizationError(err_msg)
flask_jwt_extended.exceptions.NoAuthorizationError: Missing JWT in headers or cookies (Missing Authorization Header; Missing cookie "access_token_cookie")

运行日志主要出现2个错误
签名认证失败: jwt.exceptions.InvalidSignatureError: Signature verification failed
缺少Authorization: flask_jwt_extended.exceptions.NoAuthorizationError: Missing JWT in headers or cookies

解决办法

网上关于此问题的解决资料很少,仅在stackoverflow找到这一篇https://stackoverflow.com/questions/52087743/flask-restful-noauthorizationerror-missing-authorization-header
对应中文版本https://www.thinbug.com/q/52087743

按照以下解决办法
1.将在应用程序配置中设置PROPAGATE_EXCEPTIONS:

app.config['PROPAGATE_EXCEPTIONS'] = True

2.最终解决方案是增强Flask的Api的错误处理程序。

from flask import Flask
from flask_restful import Api

class CustomApi(Api):
    def handle_error(self, e):
        for val in current_app.error_handler_spec.values():
            for handler in val.values():
                registered_error_handlers = list(filter(lambda x: isinstance(e, x), handler.keys()))
                if len(registered_error_handlers) > 0:
                    raise e
        return super().handle_error(e)

app = Flask(__name__)
api = CustomApi(app, prefix='/api/v2') # same params can be passed here

按上面的修改后,重新部署,问题解决

 类似资料: