Django DRF認證元件流程實現原理詳解
阿新 • • 發佈:2020-08-19
檢視函式中加上認證功能,流程見下圖
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,**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返回兩個值,流程結束。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。