DRF登入認證元件

2022-08-12 22:00:15 字數 1678 閱讀 2286

1.寫乙個登入認證類(類名隨意,類中的方法名固定)

from rest_framework import exceptions

from rest_framework.authentication import baseauthentication

class auth(baseauthentication):

def authenticate(self,request):

token = request.query_params.get('token')

res = models.token.objects.filter(token=token).first()

if res:

#放回的res.user就是將user新增到request中user中,res會新增到request的auth中

return res.user,res

else:

raise exceptions.apiexception('您還沒有登入!')

2.全域性使用

​ 在setting中配置

rest_framework =
​ 每次走檢視行數之前都會先走認證類

3.區域性禁用(在檢視類中新增)

authentication_classes = [ ]
例如:

​ 這樣login檢視類就不會使用auth認證

class login(apiview):

authentication_classes = [ ]

def post(self,request):

user = models.user.objects.filter(name=request.data.get('name'),pwd=request.data.get('pwd')).first()

if not user:

return jsonresponse()

else:

token = uuid.uuid4()

models.token.objects.update_or_create(user=user,defaults=)

return jsonresponse()

4.區域性使用

​ 如果要實現區域性使用就不能在setting中配置了,

​ 在要使用的檢視類中新增如下字段

authentication_classes = [auth, ]
​ 例如:

class login(apiview):

authentication_classes = [auth, ]

def post(self,request):

user = models.user.objects.filter(name=request.data.get('name'),pwd=request.data.get('pwd')).first()

if not user:

return jsonresponse()

else:

token = uuid.uuid4()

models.token.objects.update_or_create(user=user,defaults=)

return jsonresponse()

drf 認證元件

目錄區域性使用 全域性使用 原始碼分析 使用場景 有些介面在進行訪問時,需要確認使用者是否已經登入,比如 使用者需要購買物品時,在結賬的時候,就需要進行登入驗證的。一般使用者認證都是基於角色認證 使用者表關聯角色表,角色表關聯許可權表 五表機制 使用者表與角色表多對多 角色表與許可權表多對多 dja...

drf元件之jwt認證

全稱 json web token 解釋 加密字串的原始資料是json,後台產生,通過web傳輸給前台儲存 格式 三段式 頭.載荷.簽名 頭和載荷用的是base64可逆加密,簽名用md5不可逆加密 內容 頭 基礎資訊,也可以為空 加密方式 公司資訊 專案組資訊 載荷 核心資訊 使用者資訊 過期時間 ...

drf 三大認證之 認證元件

原始碼分析 1 apiview的dispath self,request,args,kwargs 2 dispath方法內 self.initial request,args,kwargs 進入三大認證 認證元件 校驗使用者 遊客 合法使用者 非法使用者 非法使用者 代表校驗失敗,丟擲異常,返回40...