drf三大认证

源码分析数据库

  dispath方法内 self.initial(request, *args, **kwargs) 进入三大认证django

        # 认证组件:校验用户(游客,合法用户,非法用户)
        # 游客:表明校验经过直接进入下一步校验,
        # 合法用户:表明校验经过,将用户存储在request.user中,在进入下一步校验
        # 非法用户:表明校验失败,抛出异常,返回403权限异常结果
        self.perform_authentication(request)
        # 权限组件:校验用户权限,必须登陆,全部用户登陆读写,游客只读,自定义用户角色
        # 认证经过:能够进入下一步校验
        # 认证失败:抛出异常,返回403权限异常结果
        self.check_permissions(request)
        # 频率组件:限制视图接口被访问的频率次数  限制的条件
        # 没有达到限次:正常访问接口
        # 达到限次:限制时间内不能访问,限制时间到达后,能够从新访问
        self.check_throttles(request)    

认证组件api

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)
                )

权限六表分析ide

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.pypost

# 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)

自定义认证类url

settings.pyspa

# drf配置
REST_FRAMEWORK = {
    # 认证类配置
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        'api.authentications.MyAuthentication',
        ],
}

authentications.pyrest

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')

 自定义频率类

  自定义一个继承 SimpleRateThrottle 类 的频率类,设置一个 scope 类属性,属性值为任意见名知意的字符串,在settings配置文件中,配置drf的DEFAULT_THROTTLE_RATES,格式为 {scope字符串: '次数/时间'},在自定义频率类中重写 get_cache_key 方法

settings.py

REST_FRAMEWORK = {
     # 频率限制条件配置
    'DEFAULT_THROTTLE_RATES': {
        'sms':'3/min'
    },
}

api/url.py

urlpatterns = [
    url(r'^sms/$', views.TestSMSAPIView.as_view()),
]

api/throttles.py

from rest_framework.throttling import SimpleRateThrottle
class SMSRateThrottle(SimpleRateThrottle):
    scope = 'sms'
    # 只对提交手机号的get方法进行限制
    def get_cache_key(self, request, view):
        mobile = request.query_params.get('mobile')
        # 没有手机,不作频率限制
        if not mobile:
            return None
        # 返回能够根据手机号变化,且不易重复的字符串,做为操做缓存的key
        return 'throttle_%(scope)s_%(ident)s' % {'scope': self.scope, 'ident': mobile}

views.py

class TestSMSAPIView(APIView):
    # 局部配置频率校验
    throttle_classes = [SMSRateThrottle]
    def get(self, request, *args, **kwargs):
        return APIResponse(0,'get 获取验证码 OK')
    def post(self, request, *args, **kwargs):
        return APIResponse(0,'post 获取验证码 OK')