DRF 全域性認證

2022-07-10 09:21:15 字數 2114 閱讀 5593

auth.py:

from rest_framework.authentication import baseauthentication

# 用於全域性認證

class globalauthentication(baseauthentication):

def authenticate(self, request):

return ("admin", "admin")

def authenticate_header(self, request):

pass

# 用於區域性認證

class myauthentication(baseauthentication):

def authenticate(self, request):

return ("test", "test")

def authenticate_header(self, request):

pass

在 settings.py 中設定全域性認證:

rest_framework =
這裡用的是認證類的路徑

# 訂單資訊

order_dict = ,

2: ,

}class orderview(apiview):

"""檢視訂單

"""def get(self, request, *args, **kwargs):

print(request.user)

print(request.auth)

response =

try:

response["data"] = order_dict

except exception as e:

pass

return jsonresponse(response)

執行結果

列印的內容:

說明現在用的是全域性認證類 globalauthentication

要是不想用全域性認證,而想用區域性認證,則可以用 authentication_classes 進行覆蓋

from drf.utils.auth import myauthentication

order_dict = ,

2: ,

}class orderview(apiview):

"""檢視訂單

"""# 設定區域性認證類,覆蓋全域性認證類

authentication_classes = [myauthentication, ]

def get(self, request, *args, **kwargs):

print(request.user)

print(request.auth)

response =

try:

response["data"] = order_dict

except exception as e:

pass

return jsonresponse(response)

列印結果:

如果既不想用全域性認證,也不想用區域性認證,則可以使用 authentication_classes = 來進行置空

DRF 版本 認證

rest framework urlpatterns url r versions myview.as view url r p v1 v2 test01 testview.as view class testview apiview def get self,request,args,kwargs...

drf 認證元件

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

DRF登入認證元件

1.寫乙個登入認證類 類名隨意,類中的方法名固定 from rest framework import exceptions from rest framework.authentication import baseauthentication class auth baseauthenticat...