源码分析
dispath方法内 self.initial(request, *args, **kwargs) 进入三大认证
# 认证组件:校验用户(游客,合法用户,非法用户) # 游客:代表校验通过直接进入下一步校验, # 合法用户:代表校验通过,将用户存储在request.user中,在进入下一步校验 # 非法用户:代表校验失败,抛出异常,返回403权限异常结果 self.perform_authentication(request) # 权限组件:校验用户权限,必须登录,所有用户登录读写,游客只读,自定义用户角色 # 认证通过:可以进入下一步校验 # 认证失败:抛出异常,返回403权限异常结果 self.check_permissions(request) # 频率组件:限制视图接口被访问的频率次数 限制的条件 # 没有达到限次:正常访问接口 # 达到限次:限制时间内不能访问,限制时间到达后,可以重新访问 self.check_throttles(request)
认证组件
def _authenticate(self): # 遍历拿到一个个认证器,进行认证 # self.authenticators配置的一堆认证类产生的认证类对象组成的 list for authenticator in self.authenticators: try: # 认证器(对象)调用认证方法authenticate(认证类对象self, request请求对象) # 返回值:登陆的用户与认证的信息组成的 tuple # 该方法被try包裹,代表该方法会抛异常,抛异常就代表认证失败 user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise # 返回值的处理 if user_auth_tuple is not None: self._authenticator = authenticator # 如何有返回值,就将 登陆用户 与 登陆认证 分别保存到 request.user、request.auth self.user, self.auth = user_auth_tuple return # 如果返回值user_auth_tuple为空,代表认证通过,但是没有 登陆用户 与 登陆认证信息,代表游客 self._not_authenticated()
权限组件
self.check_permissions(request) 认证细则: def check_permissions(self, request): # 遍历权限对象列表得到一个个权限对象(权限器),进行权限认证 for permission in self.get_permissions(): # 权限类一定有一个has_permission权限方法,用来做权限认证的 # 参数:权限对象self、请求对象request、视图类对象 # 返回值:有权限返回True,无权限返回False if not permission.has_permission(request, self): self.permission_denied( request, message=getattr(permission, ‘message‘, None) )
权限六表分析
models.py
from django.db import models # Create your models here. # 如果自定义User表后,再另一个项目中采用原生User表,完成数据迁移时,可能失败 # 1.卸载Django,重新装 # 2.将Django.contrib下面的admin\auth下的数据库记录文件清空 from django.contrib.auth.models import AbstractUser class User(AbstractUser): mobile = models.CharField(max_length=11,unique=True) class Meta: db_table = ‘api_user‘ verbose_name = ‘用户表‘ verbose_name_plural = verbose_name def __str__(self): return self.username
t_model.py
# django脚本话启动 import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day74.settings") django.setup() from api import models user = models.User.objects.first() # print(user.username) # print(user.groups.first().name) # print(user.user_permissions.first().name) from django.contrib.auth.models import Group group = Group.objects.first() # print(group.name) # print(group.user_set.first().username) # print(group.permissions.first().name) from django.contrib.auth.models import Permission p_16 = Permission.objects.filter(pk=16).first() print(p_16.user_set.first().username) p_17 = Permission.objects.filter(pk=17).first() print(p_17.group_set.first().name)
自定义认证类
settings.py
# drf配置 REST_FRAMEWORK = { # 认证类配置 ‘DEFAULT_AUTHENTICATION_CLASSES‘: [ # ‘rest_framework.authentication.SessionAuthentication‘, # ‘rest_framework.authentication.BasicAuthentication‘, ‘api.authentications.MyAuthentication‘, ], }
authentications.py
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from . import models class MyAuthentication(BaseAuthentication): # 同前台请求拿认证信息auth,没有auth是游客,返回None # 有auth进行校验 失败是非法用户抛异常,成功是合法用户,返回(用户,认证信息) def authenticate(self, request): # 前台在请求头携带信息。默认用Authorization字段携带认证信息 # 后台固定在请求对象的META字段中HTTP_AUTHORIZATION获取 auth = request.META.get(‘HTTP_AUTHORIZATION‘,None) # 处理游客 if auth is None: return None # 设置认证字段 auth_list = auth.split() # 校验合法还是非法 if not (len(auth_list) == 2 and auth_list[0].lower() == ‘auth‘): raise AuthenticationFailed(‘认证信息有误,非法用户‘) # 合法用户需要从auth_list[1]中解析出来 if auth_list[1] != ‘abc.123.xyz‘: # 校验失败 raise AuthenticationFailed(‘用户校验失败,非法用户‘) user = models.User.objects.filter(username=‘admin‘).first() if not user: raise AuthenticationFailed(‘用户数据有误,非法用户‘) return (user, None)
系统权限类
1)AllowAny: 认证规则全部返还True:return True 游客与登陆用户都有所有权限 2) IsAuthenticated: 认证规则必须有登陆的合法用户:return bool(request.user and request.user.is_authenticated) 游客没有任何权限,登陆用户才有权限 3) IsAdminUser: 认证规则必须是后台管理用户:return bool(request.user and request.user.is_staff) 游客没有任何权限,登陆用户才有权限 4) IsAuthenticatedOrReadOnly 认证规则必须是只读请求或是合法用户: return bool( request.method in SAFE_METHODS or request.user and request.user.is_authenticated ) 游客只读,合法用户无限制
urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r‘^test‘, views.TestAPIView.as_view()),
url(r‘^test1‘, views.TestAuthenticatedAPIView.as_view()),
]
settings.py
REST_FRAMEWORK = { # 权限类配置 ‘DEFAULT_PERMISSION_CLASSES‘: [ ‘rest_framework.permissions.AllowAny‘, ], }
api/views.py
from rest_framework.views import APIView from rest_framework.generics import GenericAPIView from rest_framework.viewsets import GenericViewSet,ViewSet from utils.response import APIResponse from rest_framework.permissions import IsAuthenticated class TestAPIView(APIView): def get(self, request, *args, **kwargs): return APIResponse(0, ‘test get ok‘) class TestAuthenticatedAPIView(APIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): return APIResponse(0,‘test 登录才能访问接口 ok‘)
自定义权限类
创建继承BasePermission的权限类, 实现has_permission方法, 实现体根据权限规则 确定有无权限, 进行全局或局部配置
认证规则: 满足设置的用户条件,代表有权限,返回True, 不满足设置的用户条件,代表有权限,返回False
urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r‘^test2‘, views.TestAdminOrReadOnlyAPIView.as_view()), ]
permissions.py
from rest_framework.permissions import BasePermission from django.contrib.auth.models import Group class MyPermission(BasePermission): # 只读接口判断 def has_permission(self, request, view): r1 = request.method in (‘GET‘, ‘HEAD‘, ‘OPTIONS‘) # group为当前所属的所有分组 group = Group.objects.filter(name=‘管理员‘).first() groups = request.user.groups.all() r2 = group and groups r3 = group in groups # 读接口都权限,写接口必须指定分组下的登录用户 return r1 or (r2 and r3)
views.py
# 游客只读,登录用户只读,只有登录用户属于管理员分组,才可以增删改from utils.permissions import MyPermission class TestAdminOrReadOnlyAPIView(APIView): permission_classes = [MyPermission] # 所有用户都可以访问 def get(self, request, *args, **kwargs): return APIResponse(0, ‘自定义读 OK‘) # 必须是自定义管理员分组下的用户 def post(self, request, *args, **kwargs): return APIResponse(0, ‘自定义写 OK‘)
原文地址:https://www.cnblogs.com/zrh-960906/p/11717110.html
时间: 2024-10-05 00:34:18