codebee
codebee

Reputation: 844

@jwt_required decorator not working on flask endpoint

I have a Flask Blueprint endpoint, defined as:

from flask_jwt import JWT, jwt_required, current_identity
my_api = Blueprint('MyApi', __name__)

@my_api.route("/MyApi", methods=['GET'])
@jwt_required()
def get_my_api():
    return make_response()

I have JWT configuration done in main API configuration file (other than the file that has the endpoint defined above):

app = Flask(__name__)
app.register_blueprint(my_api)
jwt = JWTManager(app)

So even though I am able to generate access_token and refresh_token but upon hitting the decorator jwt_required, I get this exception:

File "/home/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/lib/python3.6/site-packages/flask_jwt/__init__.py", line 177, in decorator
    _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
  File "/home/lib/python3.6/site-packages/flask_jwt/__init__.py", line 152, in _jwt_required
    token = _jwt.request_callback()
  File "/home/lib/python3.6/site-packages/werkzeug/local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/home/lib/python3.6/site-packages/werkzeug/local.py", line 307, in _get_current_object
    return self.__local()
  File "/home/lib/python3.6/site-packages/flask_jwt/__init__.py", line 28, in <lambda>
    _jwt = LocalProxy(lambda: current_app.extensions['jwt'])
KeyError: 'jwt'

Am I doing something wrong? Thanks.

Upvotes: 0

Views: 1935

Answers (1)

vimalloc
vimalloc

Reputation: 4167

It looks like you are mixing two different extensions. from flask_jwt import JWT, jwt_required, current_identity is the flask-jwt extension, and the jwt = JWTManager(app) is flask-jwt-extended extension. Flask-jwt has been abandoned for a long time now, so I would recommend using flask-jwt-extended in your codebase: https://flask-jwt-extended.readthedocs.io/en/stable/basic_usage.html

Upvotes: 1

Related Questions