Search code examples
pythonflaskjwtflask-restfulflask-jwt-extended

Using flask-jwt-extended callbacks with flask-restful and create_app


I'm trying to create API tokens for my flask API with flask-jwt-extended. I'm trying to initialize the token_in_blacklist_loader but can't figure out the right way to do that.

The problem is that token_in_blacklist_loader is implemented as a decorator. It is supposed to be used in the following way:

@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    jti = decrypted_token['jti']
    return jti in blacklist

^ from the docs here

Where jwt is defined as:

jwt = JWTManager(app)

But if using the create_app pattern, then jwt variable is hidden inside a function, and cannot be used in the global scope for decorators.

What is the right way to fix this / work around this?


Solution

  • What I ended up doing was putting the handler inside of create_app like so:

    def create_app(name: str, settings_override: dict = {}):
        app = Flask(name, ...)
        ...
        jwt = JWTManager(app)
        @jwt.token_in_blacklist_loader
        def check_token_in_blacklist(token_dict: dict) -> bool:
            ...