pythonflaskflask-jwt-extendedflask-jwt

How to return flask response from the middleware(app.before_request()) in flask?


I have declare a middle ware section in my application, Where am executing some code before request . In flask there are two decorator called @app.before_request and @app.after_request by using these we can declare a middle ware section . I want to validate the authentication of JWT token in middle ware .

@app.before_request
def before_request_callback():
    try:

    # Checking jwt-authentication for every request
        verify_jwt_in_request()
    except:
        #Fill this block


If something wrong in token then i want to catch that exception and return with message saying 'invalid token' . i dont want to execute further code . so how to return response from that except block ?


Solution

  • Got how to work around it .

    @app.before_request
    def before_request_callback():
        try:
            # Checking jwt-authentication for every request except login
             verify_jwt_in_request()
        except:
            return make_response(jsonify(error_dict(current_request_id(), 'Invalid token ', 401)),
                                 status.HTTP_401_UNAUTHORIZED)