用户登录
用户注册

分享至

Django REST framwork的权限验证实例

  • 作者: 我叫邢依姗
  • 来源: 51数据库
  • 2020-08-06

在这里插入代码片# Django REST framwork的权限验证

一、用户是否登录

(1)判断用户是否登录;

permission_classes = (IsAuthenticated, )

注意:permission_classes设置的是:验证的是用户是否登录、用户是否可以操作该数据等的权限;

权限组合方式,目前支持:与&(and) 或|(or) 非~(not)

例如:permission_classes = (SecAdminPermission | AudAdminPermission,)

注意:使用元组 (SecAdminPermission | AudAdminPermission,)或列表[ SecAdminPermission | AudAdminPermission]都可以。

(2)设置用户认证方式;

authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

注意:authentication_classes设置的是:用户可以通过哪种方式登录系统,例如:JWT或传统的用户名+密码方式登录。

具体代码如下:

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:
  判断某个商品是否已经收藏
 create:
  收藏商品
 delete:
  取消收藏
 """
 # 权限判断:IsAuthenticated表示是否已经登录,IsOwnerOrReadOnly表示数据是不是属于当前登录用户
 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)

 # 方法一:修改商品收藏数
 # def perform_create(self, serializer):
 #  """修改商品收藏数"""
 #  instance = serializer.save()
 #  goods = instance.goods
 #  goods.fav_num += 1
 #  goods.save()

 # 动态设置序列化类
 def get_serializer_class(self):
  if self.action == "list":
   return UserFavDetailSerializer
  elif self.action == "create":
   return UserFavSerializer

  return UserFavSerializer

二、用户是否对该数据有操作权限;

(1)自定义权限验证

前提:待验证对象有user字段;

from rest_framework import permissions

# 权限判断:数据是不是属于当前登录用户
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 写权限
  # Instance must have an attribute named `owner`.
  # return (obj.publisher if obj.publisher else self.fans )== request.user
  return obj.user== request.user # 判断当前数据是不是登录用户的数据

(2)在接口中,添加数据权限验证;

class UserFavViewset(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
      mixins.DestroyModelMixin, viewsets.GenericViewSet):
 """
 list:
  获取用户收藏列表
 retrieve:
  判断某个商品是否已经收藏
 create:
  收藏商品
  delete:
   取消收藏
 """
 # 权限判断:IsAuthenticated表示是否已经登录,IsOwnerOrReadOnly表示数据是不是属于当前登录用户
 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授权与认证

djangorestf 官方文档 授权与认证教程

permissions.py

from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
  '''
  常规的授权是 只有拥有者才能编辑它
  '''

  def has_object_permission(self, request, view, obj):
    # 读权限 向所有请求开放
    # 所以我们总是允许get, head or options requests.
    if request.method in permissions.SAFE_METHODS:
      return True

    # 写权限 只给拥有者
    return obj.owner == request.user

view.py

'''基于泛型类的视图'''
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from rest_framework import generics
from snippets.permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User

class UserList(generics.ListAPIView):
  '''
  User表的列表api视图 查 增 操作
  '''
  queryset = User.objects.all()
  serializer_class = UserSerializer

class UserDetail(generics.RetrieveDestroyAPIView):
  '''
  User表的详情api视图 查 改 删操作
  '''
  queryset = User.objects.all()
  serializer_class = UserSerializer



class 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 表示没有认证的人有读的权限,认证的人有所有权限
  # IsOwnerOrReadOnly 通过了前面的授权之后,还要通过这个授权
  # 当所有的授权都通过的时候 所有的对象实例都返回true 表示授权通过
  permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
  queryset = Snippet.objects.all()
  serializer_class = SnippetSerializer

总结:通过传递permission_classes 类变量 传递授权类,

1、请求要进行某个操作的时候 ->

2、传递参数将授权类列表中的多个授权类实例化得到实例化对象->

3、调用所有授权实例对象的has_、permission以及has_object_permission方法 ->

4、所有的返回结果都为true ->

5、该操作的授权才通过,数据操作向下继续进行。

以上这篇Django REST framwork的权限验证实例就是小编分享给大家的全部内容了,希望能给大家一个参考,

软件
前端设计
程序设计
Java相关