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

3k views Asked by At

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 ?

4

There are 4 answers

0
Vivek Kumar On BEST ANSWER

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)
1
lextiz On

As mentioned in the documentation you can return the response in the same way as it could be done normally from a Flask view code. For example:

@app.before_request
def before_request_callback():
    try:
    # Checking jwt-authentication for every request
        verify_jwt_in_request()
    except:
        return 'invalid token', 401
0
vimalloc On

For flask jwt extended you shouldn’t need to catch the exception at all. Simply having verify_jwt_in_request() should be sufficient, and it will call the default error handlers and return the appropriate response for why the token is not present or valid. You can see the default responses and customize them here: https://flask-jwt-extended.readthedocs.io/en/stable/api/#module-flask_jwt_extended

0
danangjoyoo On

you can use flask-http-middleware for it link

from flask import Flask, jsonify
from flask_http_middleware import MiddlewareManager, BaseHTTPMiddleware

app = Flask(__name__)

class AccessMiddleware(BaseHTTPMiddleware):
    def __init__(self):
        super().__init__()
    
    def dispatch(self, request, call_next):
        if request.headers.get("token") == "secret":
            return call_next(request)
        else:
            return jsonify({"message":"invalid token"})

app.wsgi_app = MiddlewareManager(app)
app.wsgi_app.add_middleware(MetricsMiddleware)

@app.get("/health")
def health():
    return {"message":"I'm healthy"}

if __name__ == "__main__":
    app.run()

Every time you make request, it will pass the middleware