使用flask-jwt-extended的自定义装饰器强制页面重定向令牌错误

问题描述 投票:0回答:1

我正在使用Flask JWT扩展库来实现JWT访问令牌。当用户的令牌过期,无效或不存在时,默认情况下Flask返回JSON,例如:

{"msg": "Missing cookie \"access_token_cookie\""}

我想制作一个包装@jwt_required的装饰器,但执行内部重定向(如登录页面),而不是像上面那样返回JSON。

这里是一个示例装饰器:

def redirect_if_error(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        jwt_data = _decode_jwt_from_request(request_type='access')

        # Do custom validation here.
        if 'identity' in jwt_data:
            authorized = True
        else:
            authorized = False

        if not authorized:
            return redirect('login', code=302)

        return view_function(*args, **kwargs)

    return jwt_required(wrapper) 

和示例页面保护页面路由,如果发生任何类型的令牌错误,我希望Flask将用户重定向到该页面路由:

@mod.route('/')
@redirect_if_error
def home():
    return render_template("index.html") 

我的问题是我无法弄清楚如何使用重定向覆盖默认的JSON返回。如果存在任何错误,则将忽略逻辑而是包装函数,并输出某种错误消息。

是否有更好的方法使用新的装饰器来覆盖默认行为?

flask-jwt-extended
1个回答
0
投票

[了解了如何使用自定义装饰器来完成此操作。只需尝试尝试捕获异常-例外,如:

def redirect_if_jwt_invalid(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        # attempt to grab the jwt from request
        try:
            jwt_data = _decode_jwt_from_request(request_type='access')
        except:
            jwt_data = None
        # if the grab worked and the identity key is in the dict then proceed
        if jwt_data and 'identity' in jwt_data:
            return view_function(*args, **kwargs)
        else:
            return redirect('login', code=302)

    return wrapper 

和路线:

from Utilities.Helpers import redirect_if_jwt_invalid

mod = Blueprint('page_routes', __name__)

@mod.route('/')
@redirect_if_jwt_invalid
def home():
    return render_template("index.html") 
© www.soinside.com 2019 - 2024. All rights reserved.