Django drf 认证基本流程

源码流程

8491383-a777d8da04e4dbb8.png
image.png
  1. 首先执行dispatch方法
  2. 重新封装Request
  3. initial(request)方法里面有各种封装函数
  4. 其中perform_authentication(request)是认证的函数
  5. 返回一个request.user
  6. def _authenticate():循环所有的authentication对象,执行authenticate方法
  7. Authtication 自定义认证类
    def authenticate():
    自定义认证
    -报错
    -返回元组(request.user, request.auth)

使用

  1. 定义一个认证类,实现authenticate方法
from rest_framework.authentication import BaseAuthentication
class FirstAuthtication(BaseAuthentication):
    def authenticate(self, request, *args, **kwargs):
        pass

    def authenticate_header(self, request):
        pass
  1. 返回值
  • 返回None, 执行下一个认证
  • 有返回值,返回一个元组,第一个参数存在request.user里,第二个在request.auth里
  • 异常
from rest_framework import exceptions
raise exceptions.AuthenticationFailed('用户认证失败')
  1. 局部使用
    相关业务
from rest_framework.views import APIView
class UserInfoView(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        print(request.user)
        return HttpResponse('用户相关信息')
  1. 全局使用
REST_FRAMEWORK = {
    # 'DEFAULT_AUTHENTICATION_CLASSES': ['apps.api.utils.auth.FirstAuthtication', 'apps.api.utils.auth.Authtication'],
    'DEFAULT_AUTHENTICATION_CLASSES': ['apps.api.utils.auth.Authtication'],
    'UNAUTHENTICATED_USER': None,
    'UNAUTHENTICATED_TOKEN': None,
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值