关于Django的登录系统
首先需要明确的是登录的本质:登录就是服务器确认当前用户的身份,并将数据库中的记录提取匹配
默认的登录系统是用户名密码方式,这种方式很平常,也没什么特别的.这里主要说的是第三方验证登录
通常第三方验证登录的过程就是用户使用第三方的账号验证系统进行登录验证,第三方验证通过后将该用户信息的取用凭据发给我们服务器,我们服务器使用该信息中用于辨识用户身份的唯一标示来记录或提取用户信息.
一般第三方登录只要绑定之后就不需要密码了,因为第三方已经帮我们处理了用户身份认证这一步骤.
所以在我们的服务器中,处理第三方登录的重点就放在了绑定和查询用户上,绑定就是在本地user表中添加一个第三方票据信息的字段,该字段是唯一的,所以通过该字段查询到的用户就是当前登录的用户.
django在自定义认证后端这一块做的特别灵活,我们可以自定义认证方式,然后在setting文件内注册一下就可以了.
AUTHENTICATION_BACKENDS = (
"app.file.classBACKEND"
)
django的登录提供一个方法,login 和认证方法 authenticate
from django.contrib.auth import login, authenticate
在使用login方法之前必须先执行authenticate方法,不然login方法会报错 user没有" backend "属性
看一下authenticate方法的源码:
def authenticate(**credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
try:
inspect.getcallargs(backend.authenticate, **credentials)
except TypeError:
# This backend doesn't accept these credentials as arguments. Try the next one.
continue try:
user = backend.authenticate(**credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be allowed in at all.
return None
if user is None:
continue
# Annotate the user object with the path of the backend.
user.backend = backend_path # 这一步给user添加了一个属性
return user # The credentials supplied are invalid to all backends, fire signal
user_login_failed.send(sender=__name__,
credentials=_clean_credentials(credentials))
这里面会调用一个方法,该方法是将配置文件中的认证后端全部扫描一遍,然后将他们放在一个列表里,再使用这列表里面所有认证后端来对数据进行认证,只要有一个认证通过,那么就认证成功.
def _get_backends(return_tuples=False):
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
'No authentication backends have been defined. Does '
'AUTHENTICATION_BACKENDS contain anything?'
)
return backends
authenticate方法内的关键一步
user = backend.authenticate(**credentials)
所以我们定义的认证后端就要实现这个方法,举例我们使用微信第三方认证, 通过unionID来认证,那么代码可以如下:
# setting文件配置:比如定义的认证后端位于 firstapp/backends.py/DSFBackend , 那么配置信息如下:
AUTHENTICATION_BACKENDS = (
"firstapp/backends.py/DSFBackend"
)
class DSFBackend(ModelBackend):
def authenticate(self, unionid=None, **kwargs):
if unionid:
try:
user = User.objects.get(unionid=unionid, status=User.STATUS_VALID)
return user
except User.DoesNotExist:
return None
except Exception:
user = User.objects.filter(unionid=unionid, status=User.STATUS_VALID).first()return user
else:
return None
这样之后就可以进行login方法进行登录了
def login(request, user):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
request.session.get(HASH_SESSION_KEY) != session_auth_hash):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = user.backend # 这一块就是很多报错的原因,如果不行authenticate方法的话,是没有backend属性的
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
可以看到,Django框架给我们做了很多工作,真的是最脏最累的活都被它干了.
关于Django的登录系统的更多相关文章
- django 快速实现完整登录系统
django 实现完整登录系统 本操作的环境: =================== Windows 7 64 python3.5 Django 1.10 =================== 创 ...
- Django用户登录与注册系统
一.创建项目 1.1.创建项目和app python manage.py startproject mysite_login python manage.py startapp login 1.2.设 ...
- Django学习笔记(9)—— 开发用户注册与登录系统
一,项目题目: 开发用户注册与登录系统 该项目主要练习使用Django开发一个用户注册与登录的系统,通过这个项目然后巩固自己这段时间所学习的Django知识. 二,项目需求: 开发一个简单的用户登录与 ...
- Django+bootstrap+注册登录系统
转自:https://www.cnblogs.com/robindong/p/9610057.html Robin_D 博客园 首页 新随笔 联系 订阅 管理 随笔 - 10 文章 - 0 评论 ...
- Django之认证系统
Django之认证系统 cookie和session 1.cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此cookie就是在这样一个场景下诞 ...
- Django的认证系统—auth模块
Django的认证系统 auth模块的知识点总结: 1. 创建超级用户 python manage.py createsuperuser from django.contrib import auth ...
- django用户认证系统——重置密码7
当用户不小心忘记了密码时,网站需要提供让用户找回账户密码的功能.在示例项目中,我们将发送一封含有重置用户密码链接的邮件到用户注册时的邮箱,用户点击收到的链接就可以重置他的密码,下面是具体做法. 发送邮 ...
- django用户认证系统——修改密码6
再此之前我们已经完成了用户登录.注册.注销等功能,接下来让我们继续为用户提供修改密码的功能.该功能 Django 的 auth 应用也已经为我们提供,过程几乎和之前的登录功能完全一样. 编写修改密码模 ...
- django用户认证系统——基本设置1
网站提供登录.注册等用户认证功能是一个常见的需求.因此,Django 提供了一套功能完整的.灵活的.易于拓展的用户认证系统:django.contrib.auth.在本教程中,我将向你展示 auth ...
随机推荐
- CodeForces B. The least round way(dp)
题目链接:http://codeforces.com/problemset/problem/2/B B. The least round way time limit per test 5 secon ...
- Create an ASP.NET Core web app in Visual Studio Code
https://www.microsoft.com/net/core#windowscmd https://download.microsoft.com/download/B/9/F/B9F1AF57 ...
- 判断DataGridView滚动条是否滚动到当前已加载的数据行底部
private void dataGridView1_Scroll(object sender, ScrollEventArgs e) { if (e.ScrollOrientation == S ...
- CentOS 源设置
安装完CentOS后,系统默认的源可能有限满,这时我们需要添加国内比较好的源. 一.国内比较好的源https://opsx.alibaba.com/mirror #阿 ...
- 使用Excel VBA(快捷键)(加菜单)
将excel宏安全性调到中: 按alt+f11进入vba编辑器: 记住以下快捷键: F7 代码窗口 F4 属性窗口 ctrl+R 工程资源窗口 F5 程序运行 TAb 代码缩进 SHIFT+TAB ...
- .netcore2.1开发部署及在centos7.x下的部署
.netcore2.1的优势毋容置疑,具体的性能建议去实际test对比,相对于之前的.netfx不知道快了多少.选择C#作为后端开发语言,主要基于以下三点: 1)代码优雅 : 2)快速搭建一套小型企业 ...
- log4j+slf4j迁移到log4j2+slf4j (Servlet3.0)
近期对系统中的旧项目实现log升级,选择了log4j2来取代log4j.作为最新一代的log实现.log4j2好在那里能够直接看log4j2性能章节. 这里写写怎样从log4j升级到log4j2. 1 ...
- 用Maven创建SpringMVC项目
IDE:Eclipse Jee JDK:8 Tomcat:8 1.创建项目 File->New->Maven Project-> ->Next-> ->Next-& ...
- QVBoxLayout移除控件之后没有消失
想在QWidget里面动态的添加和删除控件,给QWidget设置了一个布局管理器QVBoxLayout,要删除控件可以 使用QVBoxLayout::removeWidget(QWidget *w)方 ...
- OSX: 禁止iCloud钥匙链?
自从10.9有了一个新的功能叫viewlocale=zh_CN">iCloud钥匙串的,就出现了不少的麻烦.一是在10.9.3之前.好多人出现无限循环地要求用户输入Local item ...