-
認證
1.全局配置
在setting.py進行配置。
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', # 基本認證:賬號密碼認證 'rest_framework.authentication.SessionAuthentication', # session 認證 ) }
2.針對一個視圖設置
from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.views import APIView class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) ...
-
使用方法
- request.user
- 認證通過: AbstractUser對象
- 未認證通過: AnonymousUser對象
request.user.is_authenticated(): 是否認證/登錄通過
-
權限
權限控制可以限制用戶對於視圖的訪問和對於具體數據對象的訪問。
- 在執行視圖的dispatch()方法前,會先進行視圖訪問權限的判斷
在通過get_object()獲取具體對象時,會進行對象訪問權限的判斷
提供的權限
- AllowAny 允許所有用戶 (默認值,允許所有用戶訪問)
- IsAuthenticated 僅通過認證的用戶
- IsAdminUser 僅管理員用戶
- IsAuthenticatedOrReadOnly 認證的用戶可以完全操作,否則只能get讀取
無權限時兩種可能的返回值:
- 401 Unauthorized 未認證
- 403 Permission Denied 權限被禁止
1.全局設置
在setting.py進行配置。
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( # 四個選項,AllowAny、IsAuthenticated、IsAdminUser、IsAuthenticatedOrReadOnly 'rest_framework.permissions.IsAuthenticated', ) }
2.針對一個視圖設置
from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class ExampleView(APIView): # 對於當前視圖中的動作,必須登錄后才能訪問 permission_classes = (IsAuthenticated,) ...
-
自定義權限
在某些時候,需要要到自定義權限。例如一個視圖里面有幾個接口,查找全部部門,查找一個部門,修改一個部門。我們想針對修改一個部門這個接口設置權限。這時候需要自定義權限。
如需自定義權限,需繼承rest_framework.permissions.BasePermission父類,並實現以下兩個任何一個方法或全部
.has_permission(self, request, view)
是否可以訪問視圖, view表示當前視圖對象
.has_object_permission(self, request, view, obj)
是否可以訪問數據對象, view表示當前視圖, obj為數據對象
具體操作如下:
class MyPermission(BasePermission): """自定義權限""" def has_permission(self, request, view): """用戶未登錄不能修改部門""" if view.action == 'update' and not request.user.is_authenticated(): return False else: return True class DepartmentViewSet(ListModelMixin,RetrieveModelMixin,UpdateModelMixin,GenericViewSet): # 使用自定義權限 permission_classes = [MyPermission] queryset = Department.objects.all() serializer_class = DepartmentSerializer