烧瓶会话值不会保存在其他请求上

时间:2020-04-19 06:19:56

标签: python amazon-web-services nginx flask uwsgi

我到处都在寻找解决方案,但无法解决我的问题。 我目前正在AWS中使用uWSGI和NGINX运行Flask应用程序。

我的烧瓶应用正在本地127.0.0.1:5000上运行。 我曾尝试添加其他问题中提到的secret_key,但这没有用。

这是我的一些代码:

app.py

from flask import Flask, request, redirect, url_for, session, abort
from flask_session import Session

app = Flask(__name__)
app.config["SESSION_TYPE"] = 'filesystem'
app.config["SESSION_FILE_DIR"] = '/var/www/test/session'

Session(app)

@app.route('/auth/login', methods=['POST'], strict_slashes=False)
def login():
    # did some validations here
    session.permanent = True
    session['is_logged_in'] = True
    return redirect(url_for('home'))

@app.route('/auth/home', methods=['GET'], strict_slashes=False)
def home():
    if session.get('is_logged_in') == None:
        return redirect('/') # will return to default page
    return render_template('home.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0')

由于session没有存储'is_logged_in'值,所以我总是被重定向到默认页面。但是它确实存储了{ permanent: True },我相信它来自session.permanent = True行。

nginx.conf 中的配置:

location /auth {
    rewrite ^/(.+) $1 break;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off:
    proxy_pass http://127.0.0.1:5000/$1$is_args$args;
}

如果有帮助,我的uWSGI正在socket = 120.0.0.1:5000中运行,而我正在使用protocol = http

当我在浏览器中检查应用程序cookie时,它已注册了session cookie。

3 个答案:

答案 0 :(得分:0)

尝试使用if session['is_logged_in'] == False

并设置会话从一开始就记录为false。在Session(app)之后的顶部添加此session['is_logged_in'] = False

编辑:

您检查会话中是否存在“ logged_in”。 登录时,请执行以下操作:

if 'logged_in' in session:
    #User logged in 

在注销时执行

session.pop('logged_in')

答案 1 :(得分:0)

经过一番乏味的研究,结果发现我只需要在{strong> uwsgi.ini 中包含plugin = python36,该变量来自uwsgi-plugin-python36(rpm)。

答案 2 :(得分:0)

我注意到 OAuth 2.0 流程中缺乏会话持久性。 SAMESITE ="Strict" 设置是导致它的原因。 在其中一个步骤中,身份提供者未能设置 cookie 并使用相同的会话 ID 进行响应。这导致在身份验证流程结束时创建了一个新会话 - 因此没有进行身份验证。

将 SAMESITE 设置为“Lax”解决了我的问题。