1. 程式人生 > >DRF框架—認證&許可權的使用

DRF框架—認證&許可權的使用

認證和許可權是一起配合使用的。

可以再配置檔案中settings配置全域性預設的認證&許可權


REST_FRAMEWORK = {
	# python中認證的配置
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',   # 基本認證
        'rest_framework.authentication.SessionAuthentication',  # session認證
    )
    # python中許可權的配置,如果沒有指明,系統預設的許可權是允許所有人訪問的
'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ) }

也可以在每個檢視中通過設定authentication_classess屬性來設定

# 從DRF框架中匯入包authentication
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView

class ExampleView
(APIView): # 在子應用中定義authentication_classes,可以寫一個也可以寫多個 # authentication_classes = (SessionAuthentication, BasicAuthentication) # 配合許可權來使用我們寫一個。 authentication_classes = [SessionAuthentication] ...

認證失敗會有兩種可能的返回值:

  • 401 Unauthorized 未認證
  • 403 Permission Denied 許可權被禁止

也可以在具體的檢視中通過permission_classes屬性來設定,如

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class ExampleView(APIView):
	# 設定允許登入使用者來進行訪問。
    permission_classes = (IsAuthenticated,)
    ...

提供的許可權

  • AllowAny 允許所有使用者
  • IsAuthenticated 僅通過認證的使用者
  • IsAdminUser 僅管理員使用者
  • IsAuthenticatedOrReadOnly 認證的使用者可以完全操作,否則只能get讀取

我們也可以自己定義許可權

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

  • .has_permission(self, request, view)

    是否可以訪問檢視, view表示當前檢視物件,如果沒有設定的話預設的是True,如果設定
    False則表示所有的使用者都不能訪問該檢視

  • .has_object_permission(self, request, view, obj)

    是否可以訪問資料物件, view表示當前檢視, obj為資料物件,控制檢視能夠訪問添加了許可權控制類的資料物件

class MyPermission(BasePermission):
	def has_permission(self, request, view)
		"""讓所有使用者都有許可權"""
		return True
    def has_object_permission(self, request, view, obj):
        """使用者是否有許可權訪問添加了許可權控制類的資料物件"""
        # 需求:使用者能夠訪問id為1,3的物件,其他的不能夠訪問
        if obj.id in (1, 3):
        	return True
        else:
        	return False

class BookInfoViewSet(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer
    # 表示登入有許可權
    permission_classes = [IsAuthenticated]
    # 表示所有使用者都有許可權,只能夠訪問id 為1,3的資料
    permission_classes = [MyPermission]