DRF的認證與許可權功能

2022-07-03 21:51:14 字數 1645 閱讀 7641

在setting.py進行配置。

rest_framework =

from rest_framework.authentication import

sessionauthentication, basicauthentication

from rest_framework.views import

apiview

class

exampleview(apiview):

authentication_classes =(sessionauthentication, basicauthentication)

...

request.user.is_authenticated(): 是否認證/登入通過

許可權控制可以限制使用者對於檢視的訪問和對於具體資料物件的訪問。

無許可權時兩種可能的返回值:

在setting.py進行配置。

rest_framework =

from rest_framework.permissions import

isauthenticated

from rest_framework.views import

apiview

class

exampleview(apiview):

#對於當前檢視中的動作,必須登入後才能訪問

permission_classes =(isauthenticated,)

...

在某些時候,需要要到自定義許可權。例如乙個檢視裡面有幾個介面,查詢全部部門,查詢乙個部門,修改乙個部門。我們想針對修改乙個部門這個介面設定許可權。這時候需要自定義許可權。

如需自定義許可權,需繼承rest_framework.permissions.basepermission父類,並實現以下兩個任何乙個方法或全部

具體操作如下:

class

mypermission(basepermission):

"""自定義許可權

"""def

has_permission(self, request, view):

"""使用者未登入不能修改部門

"""if view.action == '

update

'and

notrequest.user.is_authenticated():

return

false

else

:

return

true

class

departmentviewset(listmodelmixin,retrievemodelmixin,updatemodelmixin,genericviewset):

#使用自定義許可權

permission_classes =[mypermission]

queryset =department.objects.all()

serializer_class = departmentserializer

drf框架中認證與許可權工作原理及設定

工作原理 前台對於使用者資訊進行的判斷 1 如果前台沒有攜帶認證資訊,直接定義為遊客 2 如果前台攜帶了認證資訊並認證通過,定位為登入使用者,將登入的使用者user物件儲存在 requset.user 中 3 如果前台攜帶了認證資訊但沒有認證通過,一般都定義為遊客 4 可以自定義為非法使用者,丟擲 ...

drf認證 許可權 頻率 過濾 排序 異常處理

使用方法 1 新建乙個認證類檔案,繼承baseauthentication raise authenticationfailed 驗證失敗 else raise authenticationfailed 請求頭沒有token資訊 2 認證類區域性配置 區域性使用,在列表內發那個值認證類 區域性禁用,...

django框架 DRF工程之許可權功能

1.相對於flask,原生而言django,drf做的則更加的合理化,想要給予使用者相應的許可權,首先需要在settings中進行配置 rest framework deafault permission classes rest framework.permissions.isauthentica...