0

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

Alexey Nikonov
  • 4,958
  • 5
  • 39
  • 66
  • Maybe this will help https://flask-jwt-extended.readthedocs.io/en/stable/changing_default_behavior/ – Nishan Apr 18 '21 at 14:43
  • @NishānWickramarathna I've changed ```@jwt_required(optional=True)``` and added redirect field to the response if no correct JWT was passed. But I supposed to find something as ```@jwt_required(redirect_to='/login')``` option – Alexey Nikonov Apr 18 '21 at 14:50
  • I am not sure if there is an in-built way. If you are wondering about code duplication, you can always use a `before_request` function. – Phenomenal One Apr 18 '21 at 14:55

1 Answers1

1

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
vimalloc
  • 3,869
  • 4
  • 32
  • 45