Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

python - X-Forwarded-Proto and Flask

I have precisely the same problem described in this SO question and answer. The answer to that question is a nice work around but I don't understand the fundamental problem. Terminating SSL at the load balancer and using HTTP between the load balancer and web/app servers is very common. What piece of the stack is not respecting the X-Forwarded-Proto? Is it werkzeug? Flask? uwsgi?

In my case I'm using an AWS ELB (which sets X-Forwarded-Proto) => Nginx (which forwards along X-Forwarded-Proto to uwsgi). But in the python app I have to subclass Flask Request as described in the question I referenced above.

Since this is such a common deployment scenario, it seems that there should be a better solution. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are missing the ProxyFix() middleware component. See the Flask Proxy Setups documentation.

There is no need to subclass anything; simply add this middleware component to your WSGI stack:

# Werkzeug 0.15 and newer
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import Flask


app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)

If you have Flask installed, you have Werkzeug too, but do pin the version to >=0.15 to get the updated version of ProxyFix (Flask 1.1.0 and newer already use that version).

This component sets the WSGI scheme from the X-Forwarded-Proto header. Do read the Flask documentation I linked you to above about trusting headers and about customising the middleware to your specific situation. Above, I’ve configured it to only look at X-Forwarded-Proto, but the component can handle other X-Forwarded-* configurations too.

The default is to trust one level of X-Forwarded-For, add x_for=0 to the keyword arguments if you want to disable this.

Also note that the functionality of the ProxyFix middleware has been expanded quite significantly in Werkzeug 0.15; in addition to X-Forwarded-Proto, -For, and -Host, the X-Forwarded-Port and -Prefix headers are also consulted, all headers support multiple values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...