如何使用 LDAP3 身份验证为所有未来请求保留用户名

how to persist username for all future requests using LDAP3 authentication

我写了一篇login.views.py for LDAP3 authentication, and the application is such that once the user login successfully, it will take the user to a template with Welcome "username" displayed on the top right of all future request pages. My application configuration for this login module is __init__.py. Part of the template code regarding whether the user is authenticated is here

一旦使用 Flask 的开发服务器登录,上述所有代码都会在所有未来请求(即应用程序的不同模块)中保留用户名;但是,当我将应用程序实时部署到生产服务器 (nginx, uwsgi) 时,有时会保留用户名,有时不会保留用户名。

我在 Whosebug 上关注过两个类似的问题:first question and second question,但仍然无法解决我的问题。

如何在用户成功登录后为所有未来请求保存用户信息?

您不能在 Flask 应用程序中使用全局变量。您有一个 users 字典来存储从 LDAP 获取的用户。在开发过程中这个 "works" 因为开发服务器只使用一个进程。但是,在生产中,您很可能 运行 应用程序处于多个进程中。每个进程都有自己的 users 字典,因此只有在处理用户登录的同一进程处理请求时才会加载用户。

您需要将用户数据存储在与应用程序分开的地方,以便在每次请求期间可以在其中查找。典型示例是数据库,但在本例中您使用的是 LDAP,只需在加载程序函数中通过 id 从 LDAP 获取用户数据。如果您试图避免对 LDAP 进行查询,那么您需要一些其他外部存储来存储和获取数据,例如数据库、内存缓存、redis 等。您也可以只将用户数据放入会话中。