简体   繁体   English

如何使用Flask和flask_jwt_extended进行自定义JWT验证?

[英]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. 我想在调用@jwt_required时为令牌添加额外的验证。 I want to verify one of the claims. 我想验证其中一项索赔。 Is there away I can do this with JWTManager? 有没有我可以用JWTManager做到这一点?

Currently my code just calls: 目前我的代码只是调用:

jwt = JWTManager(app)

And I decorate the functions with: @jwt_required 我用以下函数装饰函数: @jwt_required

Off the top of my head, my inclination would be to create a custom decorator that wraps jwt_required . 在我的头顶,我倾向于创建一个包装jwt_required的自定义装饰器。

Here's a rough idea of how it might look, via the functools.wraps documentation : 通过functools.wraps文档 ,可以大致了解它的外观:

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. 这里您可以找到jwt_required的源代码。

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). 对于它的价值,flask-jwt也不支持要求索赔(即使它说它确实如此)。 https://github.com/mattupstate/flask-jwt/issues/98 https://github.com/mattupstate/flask-jwt/issues/98

EDIT: This is now available in flask-jwt-extended. 编辑:现在可以在flask-jwt-extended中使用。 https://github.com/vimalloc/flask-jwt-extended/issues/64#issuecomment-318800617 https://github.com/vimalloc/flask-jwt-extended/issues/64#issuecomment-318800617

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM