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

Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
James MV
  • 8,569
  • 17
  • 65
  • 96

2 Answers2

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.

Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
  • 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__'``` – James MV Jul 12 '17 at 13:45
  • I think this should be: ```return view_function(*args, **kwargs) return jwt_required(wrapper)``` – James MV Jul 12 '17 at 14:15
  • 1
    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. – Nathan Wailes Jul 12 '17 at 14:30
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

vimalloc
  • 3,869
  • 4
  • 32
  • 45
  • Thanks for this vimalloc. I think the solution to all my issues is to implement a decorator as suggested by Nathan above. – James MV Jul 12 '17 at 09:59
  • 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. – James MV Jul 12 '17 at 10:17