欢迎来到代码驿站!

当前位置:首页 >

Django DRF认证组件流程实现原理详解

时间:2020-08-17 13:00:07|栏目:|点击:

视图函数中加上认证功能,流程见下图

import hashlib
import time
def get_random(name):
  md = hashlib.md5()
  md.update(bytes(str(time.time()),encoding='utf-8'))
  md.update(bytes(name,encoding='utf-8'))
  return md.hexdigest()
from rest_framework.views import APIView
class Login(APIView):
  authentication_classes = [AuthLogin]
  def post(self, request, *args, **kwargs):
    response = {'status': 100, 'msg': None}
    name = request.data.get('name')
    pwd = request.data.get('pwd')
    user = models.User.objects.filter(name=name, password=pwd).first()
    if user:
      response['msg'] = '登陆成功'
      # 随机字符串可以是用户名加当前时间生成的mds
      token = get_random(name)
      # 如果有记录,就只需要更新,不需要重新插入
      # models.UserToken.objects.create(token=token,user=user)
      # 查询 更新
      # user_agent
      models.UserToken.objects.update_or_create(user=user, defaults={'token': token})
      response['token'] = token
    else:
      response['status'] = 101
      response['msg'] = '用户名或密码错误'
    return Response(response)
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import NotAuthenticated
from app01 import models
# BaseAuthentication
class AuthLogin(BaseAuthentication):
  def authenticate(self, request):
    # 封装后的request
    token = request.GET.get('token')
    # print(token)
    ret = models.UserToken.objects.filter(token=token).first()
    if ret:
      return ret.user,token
    else:
      raise NotAuthenticated('您没有登陆')

在def initial(self, request, *args, **kwargs):函数中找到认证功能

流程总结:

  • dispatch 方法里self.initial里面有个认证组件self.perform_authentication(request)
  • 到了APIview 返回了request.user (封装后的Request)
  • 去request类里找user方法,被包装成了属性,里面执行了一个方法,self._authticate方法
  • self._authticate方法里从自己的authenticators一个一个的取东西,authenticators
  • 于是查看authenticators,是初始化的时候init传过来了,self.authenticators = authenticators or()
  • 到dispatch里找初始化的时候,也就是APIView的initialize_request方法传了self.authenticators,里面是一个get_authenticators的方法
  • self.authentication_classes 是[类1,类2,类3]一个一个取,加括号执行。生成一个一个对象.最后返回到前面的Request的_authenticate方法
  • 拿到对象之后,执行user_auth_tuple = authenticator.authenticate(self)
  • 注意authenticate是需要在视图函数中自己定义的,self.user, self.auth = user_auth_tuple返回两个值,流程结束。

上一篇:openCV4.1.1+VS2019环境配置详解

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:Django DRF认证组件流程实现原理详解

本文地址:http://www.codeinn.net/misctech/3651.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有