Flask WTForm CsrfProtect 与 Nginx/Gunicorn:推荐人检查失败 - 来源不匹配

Mat*_*sen 5 python nginx csrf flask flask-wtforms

我正在将 Django 应用程序移植到 Flask,但在最后一步中遇到了此错误:将其配置为在 nginx/gunicorn 后面运行。在 Django 中,这会引发类似的错误消息。要消除 Django 中的此错误,您只需添加ALLOWED_HOSTS到设置中,但我在 Flask_wtf.csrf 的源代码中找不到任何类似的内容

当我填写POST表格并提交时,它失败并显示Bad Request Referrer checking failed - origin does not match.

flask_wtf.csrf.CsrfProtect 谷歌搜索该字符串,我找到了here的源代码。这是referrer针对进行检查host。自己手动执行该代码,我可以看到它将我的 nginx 的主机:端口与我的 Gunicorn 的主机:端口进行比较,并且它失败了,因为我的 Gunicorn 端口与 nginx 位于不同的端口上。

这是该文件中的相关源代码,其中有我的注释作为注释

# Presumably, good_referrer is Gunicorn, request.referrer is Nginx
# In Django's csrf source code, there is a list of ALLOWED_HOSTS to check against, instead
def protect(self):
    #...
    # If I change WTF_CSRF_SSL_STRICT to false, it doesn't fail
    # But I should be able to check the referrer against a list of allowed hosts
    if request.is_secure and self._app.config['WTF_CSRF_SSL_STRICT']:
        #...
        good_referrer = 'https://%s/' % request.host
            if not same_origin(request.referrer, good_referrer):
                reason = 'Referrer checking failed - origin does not match.'
                return self._error_response(reason)

#... (line 262)
def same_origin(current_uri, compare_uri):
    parsed_uri = urlparse(current_uri)
    parsed_compare = urlparse(compare_uri)

    if parsed_uri.scheme != parsed_compare.scheme:
        return False
    # The hostname includes the host:port
    # This is where I think the failure occurs
    # As Nginx is on a different port than gunicorn
    if parsed_uri.hostname != parsed_compare.hostname:
        return False

    if parsed_uri.port != parsed_compare.port:
        return False
    return True
Run Code Online (Sandbox Code Playgroud)