简体   繁体   English

Flask 应用程序不注册 jwt.user_lookup_loader,Flask-JWT-Extended

[英]Flask app doen't register jwt.user_lookup_loader, Flask-JWT-Extended

I have a Flask app with blueprints.我有一个带有蓝图的 Flask 应用程序。 It worked just fine, but than I decided to use flask_jwt_extended to handle tokens.它工作得很好,但我决定使用flask_jwt_extended来处理令牌。 It is said in docs that I can decorate method with jwt.user_lookup_loader to have current_user working.文档中说我可以用jwt.user_lookup_loader装饰方法以使current_user工作。 But for some reason calling current_user ends up with an error:但由于某种原因,调用current_user最终会出现错误:

You must provide a `@jwt.user_lookup_loader` callback to use this method

But it is there, in the same blueprint.但它就在那里,在同一个蓝图中。 There is also a method, decorated with @jwt.user_identity_loader and it works perfectly well.还有一种方法,用@jwt.user_identity_loader装饰,效果很好。 Here is a simplified version of my code:这是我的代码的简化版本:

from . import rpc, jwt
from flask_jwt_extended import current_user, jwt_required

bp = Blueprint('login_bp', __name__)

@jwt.user_identity_loader
def _user_identity_lookup(user):
    return user.id

@jwt.user_lookup_loader
def _user_lookup_callback(_jwt_header, jwt_data):
    identity = jwt_data["sub"]
    user = rpc.cache_service.get_user(identity)
    if user is None:
        return None
    return UserSchema().load(user)

@jwt_required()
@bp.route("/logout", methods=['POST'])
def logout():
    rpc.cache_service.forget_user(current_user.id)
    return {"status": "OK"}

jwt here is JWTManager, initialized with my app: jwt 这里是 JWTManager,用我的应用程序初始化:

jwt = JWTManager()
def create_app():
    app = Flask(__name__, instance_relative_config=False)

    app.config.from_mapping(JWT_SECRET_KEY=os.environ["JWT_SECRET_KEY"])
...
    jwt.init_app(app)
...
    with app.app_context():
        from . import login_bp
        app.register_blueprint(login_bp.bp)

This code is basicly from the documentation examples:此代码基本上来自文档示例:

https://flask-jwt-extended.readthedocs.io/en/stable/automatic_user_loading/ https://flask-jwt-extended.readthedocs.io/en/stable/automatic_user_loading/

and I can't see what the problem might be (而且我看不出问题可能是什么(

Link to the repo: https://github.com/GreenBlackSky/COIN/blob/master/api_app/app/login_bp.py链接到仓库:https://github.com/GreenBlackSky/COIN/blob/master/api_app/app/login_bp.py

Your decorators are in the wrong order.您的装饰器顺序错误。 @bp.route() needs to come before @jwt_required() , otherwise it tries to evaluate the logout method when a request comes in before it decodes the JWT in the request. @bp.route()需要在@jwt_required()之前出现,否则它会在请求进入之前尝试评估logout方法,然后再解码请求中的 JWT。

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

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