Search code examples
pythonflaskjwtflask-jwt-extended

How can I do custom JWT validation with Flask and flask_jwt_extended?


I want to add additional verification to the token when @jwt_required is called. I want to verify one of the claims. Is there away I can do this with JWTManager?

Currently my code just calls:

jwt = JWTManager(app)

And I decorate the functions with: @jwt_required


Solution

  • Off the top of my head, my inclination would be to create a custom decorator that wraps jwt_required.

    Here's a rough idea of how it might look, via the functools.wraps documentation:

    from functools import wraps
    from flask_jwt_extended import jwt_required
    from flask_jwt_extended.view_decorators import _decode_jwt_from_request
    from flask_jwt_extended.exceptions import NoAuthorizationError
    
    def custom_validator(view_function):
        @wraps(view_function)
        def wrapper(*args, **kwargs):
            jwt_data = _decode_jwt_from_request(request_type='access')
    
            # Do your custom validation here.
            if (...):
                authorized = True
            else:
                authorized = False
    
            if not authorized:
                raise NoAuthorizationError("Explanation goes here")
    
            return view_function(*args, **kwargs)
    
        return jwt_required(wrapper)
    
    @app.route('/')
    @custom_validator
    def index():
        return render_template('index.html')
    

    Here is where you can find the source code for jwt_required.