我正在尝试使用 Pyramid 文档的“Making A “User Object” Available as a Request Attribute”示例制作可访问的用户数据缓存。
他们使用此代码将用户对象返回给 set_request_property:
from pyramid.security import unauthenticated_userid
def get_user(request):
# the below line is just an example, use your own method of
# accessing a database connection here (this could even be another
# request property such as request.db, implemented using this same
# pattern).
dbconn = request.registry.settings['dbconn']
userid = unauthenticated_userid(request)
if userid is not None:
# this should return None if the user doesn't exist
# in the database
return dbconn['users'].query({'id':userid})
我不明白他们为什么要使用 unauthenticated_userid(request) 从数据库中查找用户信息……这不是很不安全吗?这意味着该用户可能未登录,那么您为什么要使用该 ID 从数据库中获取私有(private)信息?
不应该
userid = authenticated_userid(request)
用来代替确保用户已登录?使用 unauthenticated_userid(request) 有什么好处?请帮助我了解这里发生了什么。
最佳答案
unauthenticated_userid
调用更便宜;它从请求中查找用户 ID,而无需再次完成整个身份验证过程。
这里的关键概念是又这个词。您应该只在已经授权的 View 中使用该方法。换句话说,当您到达使用 unauthenticated_userid
的代码时,您已经已经验证了用户,并且特别不想为这个特定调用再次执行此操作。
针对后端持久存储对用户进行身份验证可能会很昂贵,尤其是在此类存储不支持缓存的情况下。 unauthenticated_userid
API 方法是一种优化,其中请求基本上是您的 userid
缓存。
关于python - Pyramid .security : Is getting user info from a database with unauthenticated_userid(request) really secure?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12547646/