在 app 目录下创建 utils 目录,并创建 auth.py 和 permission.py 文件
auth.py:
from rest_framework.authentication import BaseAuthentication from drf import models from rest_framework.exceptions import AuthenticationFailed # 用于全局认证 class GlobalAuthentication(BaseAuthentication): def authenticate(self, request): token = request._request.GET.get("token") token_obj = models.UserToken.objects.filter(token=token).first() if not token_obj: raise AuthenticationFailed("用户认证失败") return (token_obj.user, None) def authenticate_header(self, request): pass
permission.py:
from rest_framework.permissions import BasePermission # 全局权限类 class GlobalPermission(BasePermission): # message 为没有权限时候的提示信息,也可以直接使用默认 message = "超级用户权限才能访问" def has_permission(self, request, view): if request.user.user_type == 3: return True return False # 局部权限类 class MyPermission(BasePermission): message = "管理员及以上权限才能访问" def has_permission(self, request, view): if request.user.user_type >= 2: return True return False
返回 True 即为有权限,返回 False 即为无权限
settings.py 中进行配置:
REST_FRAMEWORK = { # 全局使用的认证类 "DEFAULT_AUTHENTICATION_CLASSES": ["drf.utils.auth.GlobalAuthentication", ], # 设置 request.user "UNAUTHENTICATED_USER": None, # 设置 request.auth "UNAUTHENTICATED_TOKEN": None, # 全局使用的权限类 "DEFAULT_PERMISSION_CLASSES": ["drf.utils.permission.GlobalPermission",], }
views.py:
from django.http import JsonResponse from rest_framework.views import APIView from drf.utils.permission import MyPermission ORDER_DICT = { 1: { "commodity": "Phone", "price": 3600, "date": "2021-01-03", }, 2: { "commodity": "Computer", "price": 6700, "date": "2021-01-05", }, } class OrderView(APIView): """ 查看订单 """ def get(self, request, *args, **kwargs): response = {"code": 1000, "msg": None, "data": None} try: response["data"] = ORDER_DICT except Exception as e: pass return JsonResponse(response) USER_DICT = { 1: { "name": "John", "password": "John123", "phone": "20210103", }, 2: { "name": "Jack", "password": "Jack456", "phone": "20210105", }, } class UserinfoView(APIView): """ 查看用户信息 """ # 覆盖全局权限类 permission_classes = [MyPermission, ] def get(self, request, *args, **kwargs): response = {"code": 1000, "msg": None, "data": None} try: response["data"] = USER_DICT except Exception as e: pass return JsonResponse(response)
UserInfo 表中的数据:
UserToken 表中的数据:
访问 /order/?token=b9d56bfaeba57885b63dd0081c97c1d2,即为 admin 用户,它为管理员,但不是超级用户
访问 /order/?token=j54f28hgrtyj977439j54db7494i90l5,对应的为超级用户,符合规定的权限
访问 /userinfo/?token=e3g34hyrdrw49766h86tf4109f56t3f7,对应的为普通用户,而不是管理员及以上级别的权限
访问 /userinfo/?token=b9d56bfaeba57885b63dd0081c97c1d2,对应管理员用户
rest framework 权限中有一个内置类为 AllowAny
即允许所有权限,如果没有设置权限,这个是默认的权限