question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

AttributeError: 'AppContext' object has no attribute 'expired_jwt'

See original GitHub issue

After updating from 3.15 to 3.16 or greater, an expired token will throw the following error:

Traceback (most recent call last):
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask/app.py", line 1719, in handle_user_exception
    return handler(e)
  File "/Users/user/path/to/venv/lib/python3.7/site-packages/flask_jwt_extended/jwt_manager.py", line 99, in handle_expired_error
    token = ctx_stack.top.expired_jwt
AttributeError: 'AppContext' object has no attribute 'expired_jwt'
        @app.errorhandler(ExpiredSignatureError)
        def handle_expired_error(e):
            try:
                token = ctx_stack.top.expired_jwt #<--- explodes here
                return self._expired_token_callback(token)
            except TypeError:
                msg = (
                    "jwt.expired_token_loader callback now takes the expired token "
                    "as an additional paramter. Example: expired_callback(token)"
                )
                warn(msg, DeprecationWarning)
                return self._expired_token_callback()

I do not have a custom expired_token_loader so I’m using the default one (default_expired_token_callback)

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
vimalloccommented, Apr 10, 2019

The fix is released in version 3.18.1.

Cheers!

3reactions
xolottcommented, Apr 5, 2019

I figured out what was causing my exception, it is a call to the method decode_token on the before_request flask’s hook. This is my minimal, complete, and verifiable example based on the the one from this project docs:

from flask import Flask, jsonify, request, g
from flask_jwt_extended import (
    JWTManager,
    jwt_required,
    create_access_token,
    get_jwt_identity,
    decode_token,
)

app = Flask(__name__)

# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = 5
jwt = JWTManager(app)


@app.before_request
def _get_token():
    auth_header = request.headers.get("Authorization")
    g.token = None
    if auth_header and "Bearer" in auth_header:
        jwt_token = auth_header.split(" ")[-1]
        g.token = decode_token(jwt_token)


# Provide a method to create access tokens. The create_access_token()
# function is used to actually generate the token, and you can return
# it to the caller however you choose.
@app.route("/login", methods=["POST"])
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get("username", None)
    password = request.json.get("password", None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    if username != "test" or password != "test":
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200


# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
@app.route("/protected", methods=["GET"])
@jwt_required
def protected():
    # Access the identity of the current user with get_jwt_identity
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user), 200


if __name__ == "__main__":
    app.run()

After making a request to the /protected endpoint, prints:

...
site-packages/flask_jwt_extended/jwt_manager.py", line 99, in handle_expired_error
    token = ctx_stack.top.expired_jwt
AttributeError: 'AppContext' object has no attribute 'expired_jwt'

Env:

  • Python 3.6.7 (virtual env with pipenv)
  • Ubuntu 18.04.2

Dependencies

  • flask 1.0.2
  • flask-jwt-extended 3.18.0
Read more comments on GitHub >

github_iconTop Results From Across the Web

FlaskClient object has no attribute 'app_context' - Stack Overflow
1 Answer 1 · We got the same error, RuntimeError: working outside of application context . Also app. · @codyc4321 I edited the...
Read more >
'AppContext' object has no attribute in custom Flask extension
**Question:** AttributeError: 'AppContext' object has no attribute ... I'm using Google Proximity Beacon API to interact with beacons' data.
Read more >
Create a Flask API with JWT-Based Authentication (Part 1)
Introduction. My goal for this tutorial is to provide a detailed guide to designing and creating a Flask API that uses JSON Web...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found