I have a Flask app that uses a custom decorator to verify an AWS Cognito login token passed in an HTTP header attribute. The process includes refreshing the token (which is beyond the scope of this question). Once I get the refreshed token, I would like to update the header attribute to include the refreshed token and exit. Since the Flask/Werkzeug
request.headers property is immutable, I can’t update it by normal means.
How can I update the headers in the context of this decorator? Is there a better way that I am not thinking of?
Here’s some sample code that demonstrates the issue:
def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): token = request.headers.get('X-MyApp-Auth') if not token: return redirect(url_for('login', next=request.url)) # Test for expired token (pseudocode) if expired(token): # Refresh the token (pseudocode) new_token = refresh(refresh_token) # This is the part where the immutability gets me stuck request.headers.set('X-MyApp-Auth', new_token) return f(*args, **kwargs) return decorated_function