Search code examples
python-3.xflaskjwtwerkzeug

Is there a safe way to intercept a request in Flask, decrypt the authentication token and then mutate the request body or store in any useful context


I'm not sure if this is even possible, but I'm trying to discover patterns that would make my code more maintainable/extendable. Right now I don't like that I have to call a token decode function in every request method view function, I find the @before_request decorator being attached to a blueprint super handy but I haven't figured out how to mutate the request body so that the function can just "magically" expect the decrypted payload in the request body. If this is not intended to be permitted I can totally understand that as well from a software perspective...

I'm looking for something like this :-

Edit incoming request body payloads in flask api

Currently my setup is :

class MyMethodView(MethodView):
    def post(self):
        token = request.headers.get('token')
        identifier, is_valid = decrypt_token(token)
        # Use identifier for endpoint 

What I'd like to do is

class MyMethodView(MethodView):
    def post(self):
        identifier= request.get_json().get('identifier')
        # Use identifier for endpoint 

using the following

blueprint.@before_request():
def authenticate():
  token = request.headers.get('token')
  identifier, is_valid = decrypt(token)
  # Some how modify the request body with the identifier

  if is_valid: 
    return None
  else:
    #Unauthorized

I guess some of my curiosity revolves around whether there is a better way to do this as opposed to adding the auth check logic to every function, from my perspective I could build a few public endpoints to test locally and then just slap on some code without modifying those functions to add authentication.


Solution

  • You can store the decoded token in the flask.g object in your before_action to make it available for the lifetime of that request. https://flask.palletsprojects.com/en/1.1.x/appcontext/