Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
Daniel Kats Avatar asked Feb 28 '18 22:02

Daniel Kats


2 Answers

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:
        ...
like image 199
Daniel Kats Avatar answered Oct 21 '22 01:10

Daniel Kats


Put the JWTManager in a different file, and initialize it with the jwt.init_app function

As an example, see:

https://github.com/vimalloc/flask-jwt-extended/blob/master/examples/database_blacklist/extensions.py

and

https://github.com/vimalloc/flask-jwt-extended/blob/master/examples/database_blacklist/app.py

like image 43
vimalloc Avatar answered Oct 21 '22 01:10

vimalloc