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

2

5

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

Greisen answered 6/7, 2017 at 17:3 Comment(0)
A
6

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.

Auburn answered 6/7, 2017 at 18:24 Comment(3)
This looks really good Nathan and helps me with the next step of adding role based validation. The only issue is where you return jwt_required results in the error: 'tuple' object has no attribute '__module__'Greisen
I think this should be: return view_function(*args, **kwargs) return jwt_required(wrapper)Greisen
I never ran the code, so I'm not surprised it hit an error. Feel free to continue to edit this answer to reflect what ends up working.Auburn
P
1

Posted this in your other question, but I'll post it here too just in case others stumble upon this.

Author here. For what it's worth, flask-jwt doesn't support requiring claims either (even though it says it does). https://github.com/mattupstate/flask-jwt/issues/98

EDIT: This is now available in flask-jwt-extended. https://github.com/vimalloc/flask-jwt-extended/issues/64#issuecomment-318800617

Cheers

Puce answered 6/7, 2017 at 18:28 Comment(2)
Thanks for this vimalloc. I think the solution to all my issues is to implement a decorator as suggested by Nathan above.Greisen
I'll raise issue on github as I think adding the support for requiring claims would be a great, especially the feature that flask-jwt thinks it has for being able to extend the list of required parameters.Greisen

© 2022 - 2024 — McMap. All rights reserved.