Django REST framwork的權(quán)限驗證實例
在這里插入代碼片# Django REST framwork的權(quán)限驗證
一、用戶是否登錄
(1)判斷用戶是否登錄;
permission_classes = (IsAuthenticated, )
注意:permission_classes設置的是:驗證的是用戶是否登錄、用戶是否可以操作該數(shù)據(jù)等的權(quán)限;
權(quán)限組合方式,目前支持:與&(and) 或|(or) 非~(not)
例如:permission_classes = (SecAdminPermission | AudAdminPermission,)
注意:使用元組 (SecAdminPermission | AudAdminPermission,)或列表[ SecAdminPermission | AudAdminPermission]都可以。
(2)設置用戶認證方式;
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
注意:authentication_classes設置的是:用戶可以通過哪種方式登錄系統(tǒng),例如:JWT或傳統(tǒng)的用戶名+密碼方式登錄。
具體代碼如下:
from rest_framework.permissions import IsAuthenticated # 判斷用戶是否登錄from rest_framework_jwt.authentication import JSONWebTokenAuthentication # jwt用戶認證class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): ''' list: 獲取用戶收藏列表 retrieve: 判斷某個商品是否已經(jīng)收藏 create: 收藏商品 delete: 取消收藏 ''' # 權(quán)限判斷:IsAuthenticated表示是否已經(jīng)登錄,IsOwnerOrReadOnly表示數(shù)據(jù)是不是屬于當前登錄用戶 permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) # 用戶認證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) # 定義通過哪個參數(shù)來定位實例 lookup_field = 'goods_id' # 在詳細頁面時,搜索goods_id來確認該商品有沒有被收藏,是在當前用戶下進行搜索的 def get_queryset(self): '''獲取當前登錄用戶的收藏信息''' return UserFav.objects.filter(user=self.request.user) # 方法一:修改商品收藏數(shù) # def perform_create(self, serializer): # '''修改商品收藏數(shù)''' # instance = serializer.save() # goods = instance.goods # goods.fav_num += 1 # goods.save() # 動態(tài)設置序列化類 def get_serializer_class(self): if self.action == 'list': return UserFavDetailSerializer elif self.action == 'create': return UserFavSerializer return UserFavSerializer
二、用戶是否對該數(shù)據(jù)有操作權(quán)限;
(1)自定義權(quán)限驗證
前提:待驗證對象有user字段;
from rest_framework import permissions# 權(quán)限判斷:數(shù)據(jù)是不是屬于當前登錄用戶class IsOwnerOrReadOnly(permissions.BasePermission): ''' Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. ''' def has_object_permission(self, request, view, obj): # 1 只讀 # Read permissions are allowed to any request, # so we’ll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: # 是不是安全的訪問方法 return True # 2 寫權(quán)限 # Instance must have an attribute named `owner`. # return (obj.publisher if obj.publisher else self.fans )== request.user return obj.user== request.user # 判斷當前數(shù)據(jù)是不是登錄用戶的數(shù)據(jù)
(2)在接口中,添加數(shù)據(jù)權(quán)限驗證;
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): ''' list: 獲取用戶收藏列表 retrieve: 判斷某個商品是否已經(jīng)收藏 create: 收藏商品 delete: 取消收藏 ''' # 權(quán)限判斷:IsAuthenticated表示是否已經(jīng)登錄,IsOwnerOrReadOnly表示數(shù)據(jù)是不是屬于當前登錄用戶 permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) # 用戶認證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) # 設置 lookup_field = 'goods_id' # 在詳細頁面時,搜索goods_id來確認該商品有沒有被收藏,是在當前用戶下進行搜索的 def get_queryset(self): '''獲取當前登錄用戶的收藏信息''' return UserFav.objects.filter(user=self.request.user)
補充知識:django rest framework api授權(quán)與認證
djangorestf 官方文檔 授權(quán)與認證教程
permissions.py
from rest_framework import permissionsclass IsOwnerOrReadOnly(permissions.BasePermission): ’’’ 常規(guī)的授權(quán)是 只有擁有者才能編輯它 ’’’ def has_object_permission(self, request, view, obj): # 讀權(quán)限 向所有請求開放 # 所以我們總是允許get, head or options requests. if request.method in permissions.SAFE_METHODS: return True # 寫權(quán)限 只給擁有者 return obj.owner == request.user
view.py
’’’基于泛型類的視圖’’’from snippets.models import Snippetfrom snippets.serializers import SnippetSerializer, UserSerializerfrom rest_framework import genericsfrom snippets.permissions import IsOwnerOrReadOnlyfrom django.contrib.auth.models import Userclass UserList(generics.ListAPIView): ’’’ User表的列表api視圖 查 增 操作 ’’’ queryset = User.objects.all() serializer_class = UserSerializerclass UserDetail(generics.RetrieveDestroyAPIView): ’’’ User表的詳情api視圖 查 改 刪操作 ’’’ queryset = User.objects.all() serializer_class = UserSerializerclass SnippetList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] queryset = Snippet.objects.all() serializer_class = SnippetSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user)class SnippetDetail(generics.RetrieveDestroyAPIView): # detail 所有人都能讀,但是只有擁有者可以更改 # permissions.IsAuthenticatedOrReadOnly 表示沒有認證的人有讀的權(quán)限,認證的人有所有權(quán)限 # IsOwnerOrReadOnly 通過了前面的授權(quán)之后,還要通過這個授權(quán) # 當所有的授權(quán)都通過的時候 所有的對象實例都返回true 表示授權(quán)通過 permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] queryset = Snippet.objects.all() serializer_class = SnippetSerializer
總結(jié):通過傳遞permission_classes 類變量 傳遞授權(quán)類,
1、請求要進行某個操作的時候 ->
2、傳遞參數(shù)將授權(quán)類列表中的多個授權(quán)類實例化得到實例化對象->
3、調(diào)用所有授權(quán)實例對象的has_、permission以及has_object_permission方法 ->
4、所有的返回結(jié)果都為true ->
5、該操作的授權(quán)才通過,數(shù)據(jù)操作向下繼續(xù)進行。
以上這篇Django REST framwork的權(quán)限驗證實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php使用正則驗證密碼字段的復雜強度原理詳細講解 原創(chuàng)2. 基于javaweb+jsp實現(xiàn)企業(yè)車輛管理系統(tǒng)3. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. Jsp servlet驗證碼工具類分享6. jscript與vbscript 操作XML元素屬性的代碼7. 基于PHP做個圖片防盜鏈8. Jsp+Servlet實現(xiàn)文件上傳下載 文件列表展示(二)9. asp.net core 認證和授權(quán)實例詳解10. XML在語音合成中的應用
