Can i append a value to my flask request object in the @app.before_request and pass it forward to the endpoint view function?

Viewed 1309

I am developing some basic REST APIs in python. I am expecting an authorization token in the header of all requests except some unsecured requests like login and register. I am validating the token in @app.before_request and then I want to pass the decoded payload to the corresponding endpoint view function. But, I am not to attach the decoded info to the request object as I get "TypeError: 'Request' object does not support item assignment".

@app.before_request
def before_request():
    print(request.endpoint)
    if request.endpoint=="register" or request.endpoint=="login":
        pass
    else:
        auth_header = request.headers.get('Authorization')
        if auth_header:
            auth_token = auth_header.split(" ")[1]
            token=decode_auth_token(auth_token)
            request["token"]=token
        else:
            return jsonify({"result":"","error":"No token present in header !"})

I am thinking of this implementation like an auth filter where all requests pass this filter. I can strike off the ill requests at this layer itself and also, I can fetch the user specific info which is needed in the net middleware.

1 Answers

I have a similar usecase (surprisingly similar, actually). I got around it by setting a custom property in the request object, much like your approach, although instead of using direct assignment (i.e. request["token"]=token), I used setattr(request, "token", token).

I got the tip from a bottle plugin which does something very similar: https://github.com/agile4you/bottle-jwt/blob/master/bottle_jwt/auth.py#L258

You may even wanna try that, or some other plugin to further improve your application.

Related