What is the best practice for changing headers in a Flask request? What is the best practice for changing headers in a Flask request? flask flask

What is the best practice for changing headers in a Flask request?


This example wraps the Flask application in a custom WSGI middleware that modifies the WSGI environment before Flask request handling:

from flask import Flask, request, jsonifyclass InterceptRequestMiddleware:    def __init__(self, wsgi_app):        self.wsgi_app = wsgi_app    def __call__(self, environ, start_response):        environ['HTTP_USER_AGENT'] = 'foobar'        return self.wsgi_app(environ, start_response)app = Flask(__name__)app.wsgi_app = InterceptRequestMiddleware(app.wsgi_app)@app.route('/')def index():    return jsonify({'headers': {k: v for k, v in request.headers}})if __name__ == '__main__':    app.run(debug=True)

Links:

enter image description here


request.headers are the HTTP headers your server have received from client app,So it makes sense that you could not update those.You may be looking to set response headers which can be made following this thread:How do I set response headers in Flask?


I've got the same issue - I've got a decorator that performs cleansing, authentication, and supplies authorization information used throughout the application.

Two design points with request.headers make them hard to work with. a) the data is immutable, b) the keys are case insensitive.

One way I've gotten around this is to copy the request headers into another data structure that has bonafide acceptable content rather than anything the hacker provides.

from requests.structures import CaseInsensitiveDictcopy = CaseInsensitiveDict()for k, v in request.headers:    copy[k] = v

This can be extended to white-list filter the necessary headers, cleaning of values as per https://owasp.org/www-project-top-ten/2017/A1_2017-Injection, and amend the parameter block with custom private information.

This method does not update the request.headers object. You should develop a pattern whereby the parameter blocks user by your application are trusted and the blocks supplied by flask are untrusted.