Issue
Is there a built-in way to redirect to login page if user comes without JWT or wrong JWT is used?
@api.route('/private', methods=['GET'])
@jwt_required()
def protected():
logged = get_jwt_identity()
return jsonify(logged_in=logged), 200
Solution
Easiest solution would probably be to change the behavior for when no token is present via the unauthorized_loader
. Something like:
@jwt.unauthorized_loader
def custom_unauthorized_response(_err):
return redirect(url_for('login'))
If you needed some more fined grained control, you could use a before_request
in conjunction with verify_jwt_in_request()
. Or create your own custom decorator, something like:
def jwt_or_redirect():
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
verify_jwt_in_request(optional=True)
if not get_jwt_identity():
return redirect(url_for('login'))
else:
return fn(*args, **kwargs)
return decorator
return wrapper
Answered By - vimalloc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.