环球ug客户端:10.DRF-认证

admin 2个月前 (06-21) 科技 24 0

Django rest framework源码剖析(1)----认证

一、基础

1.1.安装

两种方式:

  • github
  • pip直接安装
pip install djangorestframework

1.2.需要先领会的一些知识

明白下面两个知识点非常重要,django-rest-framework源码中四处都是基于CBV和面向工具的封装

(1)面向工具封装的两大特征

把统一类方式封装到类中

将数据封装到工具中

(2)CBV

基于反射实现凭据请求方式差别,执行差别的方式

原理:url-->view方式-->dispatch方式(反射执行其它方式:GET/POST/PUT/DELETE等等)

二、简朴实例

2.1.settings

先建立一个project和一个app(我这里命名为API)

首先要在settings的app中添加

INSTALLED_APPS = [
    'rest_framework',
]

2.2.url

from django.contrib import admin
from django.urls import path
from API.views import AuthView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/auth/',AuthView.as_view()),
]

2.3.models

一个保留用户的信息

一个保留用户登录乐成后的token

from django.db import models

class UserInfo(models.Model):
    USER_TYPE = (
        (1,'普通用户'),
        (2,'VIP'),
        (3,'SVIP')
    )

    user_type = models.IntegerField(choices=USER_TYPE)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)

class UserToken(models.Model):
    user = models.OneToOneField(UserInfo,on_delete=models.CASCADE)
    token = models.CharField(max_length=64)

2.4.views

用户登录(返回token并保留到数据库)

from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from API import models

def md5(user):
    import hashlib
    import time
    #当前时间,相当于天生一个随机的字符串
    ctime = str(time.time())
    m = hashlib.md5(bytes(user,encoding='utf-8'))
    m.update(bytes(ctime,encoding='utf-8'))
    return m.hexdigest()

class AuthView(object):
    def post(self,request,*args,**kwargs):
        ret = {'code':1000,'msg':None}
        try:
            user = request._request.POST.get('username')
            pwd = request._request.POST.get('password')
            obj = models.UserInfo.objects.filter(username=user,password=pwd).first()
            if not obj:
                ret['code'] = 1001
                ret['msg'] = '用户名或密码错误'
            #为用户建立token
            token = md5(user)
            #存在就更新,不存在就建立
            models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})
            ret['token'] = token
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = '请求异常'
        return JsonResponse(ret)

2.5.行使postman发请求

若是用户名和密码准确的话 会天生token值,下次该用户再登录时,token的值就会更新

数据库中可以看到token的值

当用户名或密码错误时,抛出异常

三、添加认证

基于上面的例子,添加一个认证的类

3.1.url

path('api/v1/order/',OrderView.as_view()),

3.2.views

from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from API import models
from rest_framework.request import Request
from rest_framework import exceptions
from rest_framework.authentication import BasicAuthentication

ORDER_DICT = {
    1:{
        'name':'apple',
        'price':15
    },
    2:{
        'name':'dog',
        'price':100
    }
}

def md5(user):
    import hashlib
    import time
    #当前时间,相当于天生一个随机的字符串
    ctime = str(time.time())
    m = hashlib.md5(bytes(user,encoding='utf-8'))
    m.update(bytes(ctime,encoding='utf-8'))
    return m.hexdigest()

class AuthView(object):
    '''用于用户登录验证'''
    def post(self,request,*args,**kwargs):
        ret = {'code':1000,'msg':None}
        try:
            user = request._request.POST.get('username')
            pwd = request._request.POST.get('password')
            obj = models.UserInfo.objects.filter(username=user,password=pwd).first()
            if not obj:
                ret['code'] = 1001
                ret['msg'] = '用户名或密码错误'
            #为用户建立token
            token = md5(user)
            #存在就更新,不存在就建立
            models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})
            ret['token'] = token
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = '请求异常'
        return JsonResponse(ret)


class Authentication(APIView):
    '''认证'''
    def authenticate(self,request):
        token = request._request.GET.get('token')
        token_obj = models.UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败')
        #在rest framework内部会将这两个字段赋值给request,以供后续操作使用
        return (token_obj.user,token_obj)

    def authenticate_header(self, request):
        pass

class OrderView(APIView):
    '''订单相关营业'''

    authentication_classes = [Authentication,]    #添加认证
    def get(self,request,*args,**kwargs):
        #request.user
        #request.auth
        ret = {'code':1000,'msg':None,'data':None}
        try:
            ret['data'] = ORDER_DICT
        except Exception as e:
            pass
        return JsonResponse(ret)

3.3用postman发get请求

请求的时刻没有带token,可以看到会显示“用户认证失败”

环球ug客户端:10.DRF-认证 第1张

这样就达到了认证的效果,django-rest-framework的认证是怎么实现的呢,下面基于这个例子来剖析drf的源码。

四、drf的认证源码剖析

源码流程图

环球ug客户端:10.DRF-认证 第2张

请求先到dispatch

dispatch()主要做了两件事

  • 封装request
  • 认证  

详细看我写的代码内里的注释

def dispatch(self, request, *args, **kwargs):
	"""
	`.dispatch()` is pretty much the same as Django's regular dispatch,
	but with extra hooks for startup, finalize, and exception handling.
	 """
	self.args = args
    self.kwargs = kwargs
    #对原始request举行加工,厚实了一些功效
    #Request(
    #     request,
    #     parsers=self.get_parsers(),
    #     authenticators=self.get_authenticators(),
    #     negotiator=self.get_content_negotiator(),
    #     parser_context=parser_context
    # )
    #request(原始request,[BasicAuthentications工具,])
    #获取原生request,request._request
    #获取认证类的工具,request.authticators
    #1.封装request
    request = self.initialize_request(request, *args, **kwargs)
    self.request = request
    self.headers = self.default_response_headers  # deprecate?

    try:
        #2.认证
        self.initial(request, *args, **kwargs)

        # Get the appropriate handler method
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed

        response = handler(request, *args, **kwargs)

	except Exception as exc:
        response = self.handle_exception(exc)

	self.response = self.finalize_response(request, response, *args, **kwargs)
    return self.response

4.1.reuqest

(1)initialize_request()

可以看到initialize()就是封装原始request

def initialize_request(self, request, *args, **kwargs):
    """
    Returns the initial request object.
    """
    parser_context = self.get_parser_context(request)

    return Request(
        request,
        parsers=self.get_parsers(),
        #[BasicAuthentication(),],把工具封装到request内里了
        authenticators=self.get_authenticators(),    
        negotiator=self.get_content_negotiator(), parser_context=parser_context )

(2)get_authenticators()

通过列表天生式,返回工具的列表

def get_authenticators(self):
    """
    Instantiates and returns the list of authenticators that this view can use.
    """
    return [auth() for auth in self.authentication_classes]

(3)authentication_classes

APIView内里有个 authentication_classes 字段

可以看到默认是去全局的设置文件找(api_settings)

class APIView(View):

    # The following policies may be set at either globally, or per-view.
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
    parser_classes = api_settings.DEFAULT_PARSER_CLASSES
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
    throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
    metadata_class = api_settings.DEFAULT_METADATA_CLASS
    versioning_class = api_settings.DEFAULT_VERSIONING_CLASS

4.2.认证

self.initial(request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
    """
    `.dispatch()` is pretty much the same as Django's regular dispatch,
    but with extra hooks for startup, finalize, and exception handling.
    """
    self.args = args
    self.kwargs = kwargs
    #对原始request举行加工,厚实了一些功效
    #Request(
    #     request,
    #     parsers=self.get_parsers(),
    #     authenticators=self.get_authenticators(),
    #     negotiator=self.get_content_negotiator(),
    #     parser_context=parser_context
    # )
    #request(原始request,[BasicAuthentications工具,])
    #获取原生request,request._request
    #获取认证类的工具,request.authticators
    #1.封装request
    request = self.initialize_request(request, *args, **kwargs)
    self.request = request
    self.headers = self.default_response_headers  # deprecate?

    try:
        #2.认证
        self.initial(request, *args, **kwargs)

        # Get the appropriate handler method
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed

        response = handler(request, *args, **kwargs)

	except Exception as exc:
        response = self.handle_exception(exc)

	self.response = self.finalize_response(request, response, *args, **kwargs)
    return self.response

(1)initial()

主要看 self.perform_authentication(request),实现认证

def initial(self, request, *args, **kwargs):
    """
    Runs anything that needs to occur prior to calling the method handler.
    """
    self.format_kwarg = self.get_format_suffix(**kwargs)

    # Perform content negotiation and store the accepted info on the request
    neg = self.perform_content_negotiation(request)
    request.accepted_renderer, request.accepted_media_type = neg

    # Determine the API version, if versioning is in use.
    version, scheme = self.determine_version(request, *args, **kwargs)
    request.version, request.versioning_scheme = version, scheme

    # Ensure that the incoming request is permitted
    #3.实现认证
    self.perform_authentication(request)
    self.check_permissions(request)
    self.check_throttles(request)

(2)perform_authentication()

挪用了request.user

def perform_authentication(self, request):
    """
    Perform authentication on the incoming request.

	Note that if you override this and simply 'pass', then authentication
	will instead be performed lazily, the first time either
	`request.user` or `request.auth` is accessed.
	"""
    request.user

(3)user

request.user的request的位置

环球ug客户端:10.DRF-认证 第3张

点进去可以看到Request有个user方式,加 @property 示意挪用user方式的时刻不需要加括号“user()”,可以直接挪用:request.user

@property
def user(self):
    """
    Returns the user associated with the current request, as authenticated
    by the authentication classes provided to the request.
    """
    if not hasattr(self, '_user'):
        with wrap_attributeerrors():
            #获取认证工具,举行一步步的认证
            self._authenticate()
    return self._user

(4)_authenticate()

循环所有authenticator工具

def _authenticate(self):
    """
    Attempt to authenticate the request using each authentication instance
    in turn.
    """
    #循环认证类的所有工具
    #执行工具的authenticate方式
    for authenticator in self.authenticators:
        try:
            #执行认证类的authenticate方式
            #这里分三种情形
            #1.若是authenticate方式抛出异常,self._not_authenticated()执行
            #2.有返回值,必须是元组:(request.user,request.auth)
            #3.返回None,示意当前认证不处置,等下一个认证来处置
            user_auth_tuple = authenticator.authenticate(self)
        except exceptions.APIException:
            self._not_authenticated()
            raise

        if user_auth_tuple is not None:
            self._authenticator = authenticator
            self.user, self.auth = user_auth_tuple
            return

	self._not_authenticated()

返回值就是例子中的:

token_obj.user-->>request.user
token_obj-->>request.auth
#在rest framework内部会将这两个字段赋值给request,以供后续操作使用
return (token_obj.user,token_obj)     #例子中的return

当都没有返回值,就执行self._not_authenticated(),相当于匿名用户,没有通过认证

def _not_authenticated(self):
    """
    Set authenticator, user & authtoken representing an unauthenticated request.

	Defaults are None, AnonymousUser & None.
	"""
    self._authenticator = None

    if api_settings.UNAUTHENTICATED_USER:
        self.user = api_settings.UNAUTHENTICATED_USER()   #AnonymousUser匿名用户
    else:
        self.user = None

	if api_settings.UNAUTHENTICATED_TOKEN:
        self.auth = api_settings.UNAUTHENTICATED_TOKEN()  #None
	else:
        self.auth = None

面向工具知识:

子类继续 父类,挪用方式的时刻:

  • 优先去自己内里找有没有这个方式,有就执行自己的
  • 只有当自己内里没有这个方式的时刻才会去父类找

由于authenticate方式我们自己写,以是当执行authenticate()的时刻就是执行我们自己写的认证

父类中的authenticate方式

def authenticate(self, request):
    return (self.force_user, self.force_token)

我们自己写的

class Authentication(APIView):
    '''用于用户登录验证'''
    def authenticate(self,request):
        token = request._request.GET.get('token')
        token_obj = models.UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败')
        #在rest framework内部会将这两个字段赋值给request,以供后续操作使用
        return (token_obj.user,token_obj)

认证的流程就是上面写的,弄懂了原理,再写代码就更容易明白为什么了。

4.3.设置文件

继续解读源码

环球ug客户端:10.DRF-认证 第4张

默认是去全局设置文件中找,以是我们应该在settings.py中设置好路径

api_settings源码

api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)

def reload_api_settings(*args, **kwargs):
    setting = kwargs['setting']
    if setting == 'REST_FRAMEWORK':
        api_settings.reload()

setting中‘REST_FRAMEWORK’中找

全局设置方式:

API文件夹下面新建文件夹utils,再新建auth.py文件,内里写上认证的类

settings.py

#设置全局认证
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES":['API.utils.auth.Authentication',]   #内里写你的认证的类的路径
}

auth.py

# API/utils/auth.py

from rest_framework import exceptions
from API import models


class Authentication(object):
    '''用于用户登录验证'''
    def authenticate(self,request):
        token = request._request.GET.get('token')
        token_obj = models.UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败')
        #在rest framework内部会将这两个字段赋值给request,以供后续操作使用
        return (token_obj.user,token_obj)

    def authenticate_header(self, request):
        pass

在settings内里设置的全局认证,所有营业都需要经由认证,若是想让某个不需要认证,只需要在其中添加下面的代码:

authentication_classes = []    #内里为空,代表不需要认证
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from API import models
from rest_framework.request import Request
from rest_framework import exceptions
from rest_framework.authentication import BasicAuthentication

ORDER_DICT = {
    1:{
        'name':'apple',
        'price':15
    },
    2:{
        'name':'dog',
        'price':100
    }
}

def md5(user):
    import hashlib
    import time
    #当前时间,相当于天生一个随机的字符串
    ctime = str(time.time())
    m = hashlib.md5(bytes(user,encoding='utf-8'))
    m.update(bytes(ctime,encoding='utf-8'))
    return m.hexdigest()

class AuthView(APIView):
    '''用于用户登录验证'''

    authentication_classes = []    #内里为空,代表不需要认证

    def post(self,request,*args,**kwargs):
        ret = {'code':1000,'msg':None}
        try:
            user = request._request.POST.get('username')
            pwd = request._request.POST.get('password')
            obj = models.UserInfo.objects.filter(username=user,password=pwd).first()
            if not obj:
                ret['code'] = 1001
                ret['msg'] = '用户名或密码错误'
            #为用户建立token
            token = md5(user)
            #存在就更新,不存在就建立
            models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})
            ret['token'] = token
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = '请求异常'
        return JsonResponse(ret)




class OrderView(APIView):
    '''订单相关营业'''


    def get(self,request,*args,**kwargs):
        # self.dispatch
        #request.user
        #request.auth
        ret = {'code':1000,'msg':None,'data':None}
        try:
            ret['data'] = ORDER_DICT
        except Exception as e:
            pass
        return JsonResponse(ret)

API/view.py代码

再测试一下我们的代码

不带token发请求

环球ug客户端:10.DRF-认证 第5张

带token发请求

环球ug客户端:10.DRF-认证 第6张

五、drf的内置认证

rest_framework内里内置了一些认证,我们自己写的认证类都要继续内置认证类 "BaseAuthentication"

4.1.BaseAuthentication源码:

class BaseAuthentication(object):
    """
    All authentication classes should extend BaseAuthentication.
    """

    def authenticate(self, request):
        """
        Authenticate the request and return a two-tuple of (user, token).
        """
        #内置的认证类,authenticate方式,若是不自己写,默认则抛出异常
        raise NotImplementedError(".authenticate() must be overridden.")

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        #authenticate_header方式,作用是当认证失败的时刻,返回的响应头
        pass

4.2.修改自己写的认证类

自己写的Authentication必须继续内置认证类BaseAuthentication

# API/utils/auth/py

from rest_framework import exceptions
from API import models
from rest_framework.authentication import BaseAuthentication


class Authentication(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 exceptions.AuthenticationFailed('用户认证失败')
        #在rest framework内部会将这两个字段赋值给request,以供后续操作使用
        return (token_obj.user,token_obj)

    def authenticate_header(self, request):
        pass

4.3.其它内置认证类

rest_framework内里还内置了其它认证类,我们主要用到的就是BaseAuthentication,剩下的很少用到

环球ug客户端:10.DRF-认证 第7张

六、总结

自己写认证类方式梳理

(1)建立认证类

  • 继续BaseAuthentication --->>1.重写authenticate方式;2.authenticate_header方式直接写pass就可以(这个方式必须写)

(2)authenticate()返回值(三种)

  • None ----->>>当前认证不管,等下一个认证来执行
  • raise exceptions.AuthenticationFailed('用户认证失败') # from rest_framework import exceptions
  • 有返回值元祖形式:(元素1,元素2) #元素1复制给request.user; 元素2复制给request.auth

(3)局部使用

  • authentication_classes = [BaseAuthentication,]

(4)全局使用

#设置全局认证
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES":['API.utils.auth.Authentication',]
}

源码流程

--->>dispatch

    --封装request

       ---获取界说的认证类(全局/局部),通过列表天生式建立工具 

     ---initial

       ----peform_authentication

         -----request.user (每部循环建立的工具)

,

欧博开户网址

欢迎进入欧博开户网址(Allbet Gaming):www.aLLbetgame.us,欧博网址开放会员注册、代理开户、电脑客户端下载、苹果安卓下载等业务。

皇冠APP声明:该文看法仅代表作者自己,与本平台无关。转载请注明:环球ug客户端:10.DRF-认证

网友评论

  • (*)

最新评论

文章归档

站点信息

  • 文章总数:548
  • 页面总数:0
  • 分类总数:8
  • 标签总数:1031
  • 评论总数:155
  • 浏览总数:2404