获取 django 用户后如何手动进行身份验证?
我正在编写一个 facebook-connect 应用程序,在 facebook 上验证会话后登录用户,问题是如何在获取用户对象后在 django 上验证用户?
user = User.objects.get(email=email)
user = authenticate(username=user.username, password=user.password)
login(request, user)
还有另一种方法可以实现这一目标吗?
Im writing a facebook-connect app that login user after authenticate session on facebook, question is how can i authenticate user on django after get user object?
user = User.objects.get(email=email)
user = authenticate(username=user.username, password=user.password)
login(request, user)
Is there another way to achieve this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你这样做,你实际上并不需要首先验证(但我没有告诉你!):
user.backend = 'django.contrib.auth.backends.ModelBackend'
登录(请求,用户)
You don't actually need to authenticate() first if you do this (but I didn't tell you!):
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
根据您的问题和示例,您应该查看并注意两件事。
首先,处理备用身份验证方法(例如 facebook oauth)的方式是 身份验证后端。您可以查看 djangopackages.com 了解现有选项或编写自己的选项。您配置的后端将定义
authenticate()
期望接收哪些参数(例如,facebook 后端不会期望密码,因为密码在该上下文中没有意义) )。其次,执行 user.password 不会获得用户的实际密码。作为一项安全措施,Django 将密码存储为加盐单向哈希 。这意味着,根据设计,您无法根据数据库中存储的内容确定用户的密码。
There are two things you should look at and be aware of based on your question and example.
First, the way you handle alternate authentication methods (e.g. facebook oauth) are authentication backends. You can look at djangopackages.com for existing options or write your own. The backend(s) you have configured are what will define what parameters
authenticate()
is expecting to receive (e.g. a facebook backend wouldn't expect a password as a password doesn't make sense in that context).Second, doing user.password won't get you the user's actual password. As a security measure, Django stores passwords as salted one-way hashes. This means that, by design, you cannot determine a user's password based on what is stored in the database.
authenticate()
和login()
各自提供不同的任务,并且两者(或从 Django 代码中提取的等效项并针对每个 Django 版本进行更新) 是登录用户所必需的。authenticate()
andlogin()
each provide different tasks, and both (or the equivalent pulled from the Django code and updated for each version of Django) are required in order to log a user in.