Django REST framwork的權(quán)限驗(yàn)證實(shí)例
在這里插入代碼片# Django REST framwork的權(quán)限驗(yàn)證
一、用戶是否登錄
(1)判斷用戶是否登錄;
permission_classes = (IsAuthenticated, )
注意:permission_classes設(shè)置的是:驗(yàn)證的是用戶是否登錄、用戶是否可以操作該數(shù)據(jù)等的權(quán)限;
權(quán)限組合方式,目前支持:與&(and) 或|(or) 非~(not)
例如:permission_classes = (SecAdminPermission | AudAdminPermission,)
注意:使用元組 (SecAdminPermission | AudAdminPermission,)或列表[ SecAdminPermission | AudAdminPermission]都可以。
(2)設(shè)置用戶認(rèn)證方式;
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
注意:authentication_classes設(shè)置的是:用戶可以通過哪種方式登錄系統(tǒng),例如:JWT或傳統(tǒng)的用戶名+密碼方式登錄。
具體代碼如下:
from rest_framework.permissions import IsAuthenticated # 判斷用戶是否登錄from rest_framework_jwt.authentication import JSONWebTokenAuthentication # jwt用戶認(rèn)證class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): ''' list: 獲取用戶收藏列表 retrieve: 判斷某個(gè)商品是否已經(jīng)收藏 create: 收藏商品 delete: 取消收藏 ''' # 權(quán)限判斷:IsAuthenticated表示是否已經(jīng)登錄,IsOwnerOrReadOnly表示數(shù)據(jù)是不是屬于當(dāng)前登錄用戶 permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) # 用戶認(rèn)證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) # 定義通過哪個(gè)參數(shù)來定位實(shí)例 lookup_field = 'goods_id' # 在詳細(xì)頁面時(shí),搜索goods_id來確認(rèn)該商品有沒有被收藏,是在當(dāng)前用戶下進(jìn)行搜索的 def get_queryset(self): '''獲取當(dāng)前登錄用戶的收藏信息''' return UserFav.objects.filter(user=self.request.user) # 方法一:修改商品收藏?cái)?shù) # def perform_create(self, serializer): # '''修改商品收藏?cái)?shù)''' # instance = serializer.save() # goods = instance.goods # goods.fav_num += 1 # goods.save() # 動態(tài)設(shè)置序列化類 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)限驗(yàn)證
前提:待驗(yàn)證對象有user字段;
from rest_framework import permissions# 權(quán)限判斷:數(shù)據(jù)是不是屬于當(dāng)前登錄用戶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 # 判斷當(dāng)前數(shù)據(jù)是不是登錄用戶的數(shù)據(jù)
(2)在接口中,添加數(shù)據(jù)權(quán)限驗(yàn)證;
class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): ''' list: 獲取用戶收藏列表 retrieve: 判斷某個(gè)商品是否已經(jīng)收藏 create: 收藏商品 delete: 取消收藏 ''' # 權(quán)限判斷:IsAuthenticated表示是否已經(jīng)登錄,IsOwnerOrReadOnly表示數(shù)據(jù)是不是屬于當(dāng)前登錄用戶 permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) # 用戶認(rèn)證:方式一:JSONWebTokenAuthentication;方式二:SessionAuthentication authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) # 設(shè)置 lookup_field = 'goods_id' # 在詳細(xì)頁面時(shí),搜索goods_id來確認(rèn)該商品有沒有被收藏,是在當(dāng)前用戶下進(jìn)行搜索的 def get_queryset(self): '''獲取當(dāng)前登錄用戶的收藏信息''' return UserFav.objects.filter(user=self.request.user)
補(bǔ)充知識:django rest framework api授權(quán)與認(rèn)證
djangorestf 官方文檔 授權(quán)與認(rè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 表示沒有認(rèn)證的人有讀的權(quán)限,認(rèn)證的人有所有權(quán)限 # IsOwnerOrReadOnly 通過了前面的授權(quán)之后,還要通過這個(gè)授權(quán) # 當(dāng)所有的授權(quán)都通過的時(shí)候 所有的對象實(shí)例都返回true 表示授權(quán)通過 permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] queryset = Snippet.objects.all() serializer_class = SnippetSerializer
總結(jié):通過傳遞permission_classes 類變量 傳遞授權(quán)類,
1、請求要進(jìn)行某個(gè)操作的時(shí)候 ->
2、傳遞參數(shù)將授權(quán)類列表中的多個(gè)授權(quán)類實(shí)例化得到實(shí)例化對象->
3、調(diào)用所有授權(quán)實(shí)例對象的has_、permission以及has_object_permission方法 ->
4、所有的返回結(jié)果都為true ->
5、該操作的授權(quán)才通過,數(shù)據(jù)操作向下繼續(xù)進(jìn)行。
以上這篇Django REST framwork的權(quán)限驗(yàn)證實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
