一、简单认证示例

需求:

  • 用户名密码正确:没有 token 则产生一个 token,有 token 则更新,返回登录成功;
  • 若用户名或密码错误,返回错误信息。

1、models.py

  1. from django.db import models
  2. class UserInfo(models.Model):
  3. USER_TYPE = (
  4. (1, '普通用户'),
  5. (2, 'VIP'),
  6. (3, 'SVIP')
  7. )
  8. user_type = models.IntegerField(choices=USER_TYPE)
  9. username = models.CharField(max_length=32)
  10. password = models.CharField(max_length=64)
  11. class UserToken(models.Model):
  12. user = models.OneToOneField(UserInfo, on_delete=models.CASCADE)
  13. token = models.CharField(max_length=64)

2、urls.py

  1. from django.contrib import admin
  2. from django.urls import path
  3. from app.views import IndexView
  4. urlpatterns = [
  5. path('admin/', admin.site.urls),
  6. path('index/', IndexView.as_view()),
  7. ]

3、views.py

  1. from django.shortcuts import render, HttpResponse
  2. from django.views import View
  3. import json
  4. import hashlib
  5. import time
  6. from app import models
  7. def md5(user):
  8. """加密"""
  9. ctime = str(time.time())
  10. m = hashlib.md5(bytes(user, encoding='utf-8'))
  11. m.update(bytes(ctime, encoding='utf-8'))
  12. return m.hexdigest()
  13. class IndexView(View):
  14. def post(self, request, *args, **kwargs):
  15. ret = {'code': 1000, 'msg': None}
  16. try:
  17. user = request.POST.get('username')
  18. password = request.POST.get('password')
  19. obj = models.UserInfo.objects.filter(username=user, password=password).first()
  20. if not obj:
  21. ret['code'] = 10001
  22. ret['msg'] = '用户名或密码错误'
  23. # 为用户创建token
  24. token = md5(user)
  25. # 存在就更新,不存在就创建
  26. o = models.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
  27. except Exception as e:
  28. ret['code'] = 1002
  29. ret['msg'] = '请求异常'
  30. return HttpResponse(json.dumps(ret))

利用 postman 工具模拟发送 post 请求:

二、rest framework 认证

基于上面的例子,我们用 rest framework 给每个类都实现认证功能。

1、新建一个 auth.py 脚本文件,app/utils/auth.py

  1. from rest_framework import exceptions
  2. from app import models
  3. class MyAuthentication(object):
  4. """认证类"""
  5. def authenticate(self, request):
  6. token = request._request.GET.get('token') # 获取 token
  7. token_obj = models.UserToken.objects.filter(token=token).first()
  8. if not token_obj:
  9. raise exceptions.AuthenticationFailed('用户认证失败')
  10. return (token_obj.user, token_obj) # 返回一个元组
  11. def authenticate_header(self, val):
  12. pass

2、project/urls.py

  1. from django.contrib import admin
  2. from django.urls import path
  3. from app.views import IndexView, OrderView
  4. urlpatterns = [
  5. path('admin/', admin.site.urls),
  6. path('index/', IndexView.as_view()),
  7. path('order/', OrderView.as_view()),
  8. ]

3、app/views.py

  1. from django.shortcuts import render, HttpResponse
  2. from rest_framework.views import APIView
  3. import hashlib
  4. import time
  5. from app import models
  6. from django.http import JsonResponse
  7. from .utils.auth import MyAuthentication # 导入认证的类
  8. def md5(user):
  9. """加密"""
  10. ctime = str(time.time())
  11. m = hashlib.md5(bytes(user, encoding='utf-8'))
  12. m.update(bytes(ctime, encoding='utf-8'))
  13. return m.hexdigest()
  14. # 订单信息
  15. ORDER_DICT = {
  16. 1: {
  17. 'name': 'rose',
  18. 'age': 18,
  19. 'gender': 'female'
  20. },
  21. 2: {
  22. 'name': 'tom',
  23. 'age': 19,
  24. 'gender': 'male'
  25. },
  26. }
  27. class OrderView(APIView):
  28. """订单管理"""
  29. authentication_classes = [MyAuthentication, ] # 添加认证
  30. ret = {'code': 1000, 'msg': None, 'data': None, }
  31. def get(self, request, *args, **kwargs):
  32. self.ret['data'] = ORDER_DICT
  33. return JsonResponse(self.ret)
  34. def post(self, request, *args, **kwargs):
  35. try:
  36. user = request._request.POST.get('username')
  37. pwd = request._request.POST.get('password')
  38. obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
  39. if not obj:
  40. self.ret['code'] = 1001
  41. self.ret['msg'] = '用户名或密码错误'
  42. token = md5(user)
  43. models.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
  44. self.ret['token'] = token
  45. except Exception as e:
  46. self.ret['code'] = 1002
  47. self.ret['msg'] = '请求异常'
  48. return JsonResponse(self.ret)

在视图中我们新添加了一个订单类 OrderView,现在我们用 postman 发送 get 请求:

发现认证失败,这是因为我们在认证时候获取 URL 中的 token,若过来的请求没有携带 token 就会认证失败。下面再来看看携带 token 的样子:

三、分析 DRF 源码实现认证

在这里我们将通过分析 drf 的源码来分析它是怎么实现认证的,又是怎么来编辑认证类的,下面是源码大致流程:

封装原生request 对象

1、drf 使用的 CBV 模式,所有请求过来,首先执行 dispatch() 方法,restframe work 对 dispatch() 方法增加了一些其他功能 restframework/views.py

  1. def dispatch(self, request, *args, **kwargs):
  2. """
  3. `.dispatch()` is pretty much the same as Django's regular dispatch,
  4. but with extra hooks for startup, finalize, and exception handling.
  5. """
  6. self.args = args
  7. self.kwargs = kwargs
  8. # 对原生的 request 对象进行加工,丰富了
  9. # request= Request(request,parsers=self.get_parsers(),authenticators=self.get_authenticators(),negotiator=self.get_content_negotiator(),parser_context=parser_context)
  10. # 第一个参数为原生的 request 对象,
  11. request = self.initialize_request(request, *args, **kwargs)
  12. self.request = request
  13. self.headers = self.default_response_headers # deprecate?
  14. try:
  15. # 认证
  16. self.initial(request, *args, **kwargs)
  17. # Get the appropriate handler method
  18. if request.method.lower() in self.http_method_names:
  19. handler = getattr(self, request.method.lower(),
  20. self.http_method_not_allowed)
  21. else:
  22. handler = self.http_method_not_allowed
  23. response = handler(request, *args, **kwargs)
  24. except Exception as exc:
  25. response = self.handle_exception(exc)
  26. self.response = self.finalize_response(request, response, *args, **kwargs)
  27. return self.response

从上面源码可以看到,在 dispatch() 方法中,主要做了两件事:

  • self.initialize_request(request, *args, **kwargs):对原生 request 对象进行了封装,增加了一些其他功能
  • self.initial(request, *args, **kwargs):执行认证功能

2、initialize_request()

下面我们来看看 initialize_request() 方法怎么封装原生 request 对象的:

  1. def initialize_request(self, request, *args, **kwargs):
  2. """
  3. Returns the initial request object.
  4. """
  5. parser_context = self.get_parser_context(request)
  6. return Request(
  7. request,
  8. parsers=self.get_parsers(),
  9. authenticators=self.get_authenticators(), # 这个函数将返回一个对象列表
  10. negotiator=self.get_content_negotiator(),
  11. parser_context=parser_context
  12. )

3、get_authenticators()

使用列表生成式循环 self.authentication_classes 中的对象,并执行,返回一个对象列表:

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

4、authentication_classes

api_settings 会从 settings 中匹配 DEFAULT_AUTHENTICATION_CLASSES 字段,所有可用通过在 settings 中设置 DEFAULT_AUTHENTICATION_CLASSES,可用实现全局认证:

  1. class APIView(View):
  2. # The following policies may be set at either globally, or per-view.
  3. renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
  4. parser_classes = api_settings.DEFAULT_PARSER_CLASSES
  5. # 这句,从 setting 中找 DEFAULT_AUTHENTICATION_CLASSES 字段
  6. authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
  7. ...

认证

下面我们来分析 dispatch() 中的另一个方法:initial(request, *args, **kwargs)(认证)

1、initial()

  1. def initial(self, request, *args, **kwargs):
  2. """
  3. Runs anything that needs to occur prior to calling the method handler.
  4. """
  5. self.format_kwarg = self.get_format_suffix(**kwargs)
  6. # Perform content negotiation and store the accepted info on the request
  7. neg = self.perform_content_negotiation(request)
  8. request.accepted_renderer, request.accepted_media_type = neg
  9. # Determine the API version, if versioning is in use.
  10. version, scheme = self.determine_version(request, *args, **kwargs)
  11. request.version, request.versioning_scheme = version, scheme
  12. # Ensure that the incoming request is permitted
  13. # 实现认证
  14. self.perform_authentication(request)
  15. self.check_permissions(request)
  16. self.check_throttles(request)

2、perform_authentication()

这里面就调用了 user:

  1. def perform_authentication(self, request):
  2. """
  3. Perform authentication on the incoming request.
  4. Note that if you override this and simply 'pass', then authentication
  5. will instead be performed lazily, the first time either
  6. `request.user` or `request.auth` is accessed.
  7. """
  8. request.user # 这个 request 是原生 request 对象

3、user()

user() 是一个静态方法,因此调用它是不用加括号:

  1. @property
  2. def user(self):
  3. """
  4. Returns the user associated with the current request, as authenticated
  5. by the authentication classes provided to the request.
  6. """
  7. if not hasattr(self, '_user'):
  8. with wrap_attributeerrors():
  9. # 获取认证对象,进行一步步的认证
  10. self._authenticate()
  11. return self._user

4、_authenticate()

循环所有 authenticator 对象:

  1. def _authenticate(self):
  2. """
  3. Attempt to authenticate the request using each authentication instance
  4. in turn.
  5. 循环认证类的所有对象
  6. 这里分三种情况
  7. 1.如果authenticate方法抛出异常,self._not_authenticated()执行
  8. 2.有返回值,必须是元组:(request.user,request.auth)
  9. 3.返回None,表示当前认证不处理,等下一个认证来处理
  10. """
  11. for authenticator in self.authenticators:
  12. try:
  13. # 执行认证类的authenticate方法
  14. user_auth_tuple = authenticator.authenticate(self)
  15. except exceptions.APIException:
  16. self._not_authenticated()
  17. raise
  18. if user_auth_tuple is not None:
  19. self._authenticator = authenticator
  20. # 返回一个元组
  21. self.user, self.auth = user_auth_tuple
  22. return
  23. self._not_authenticated()

authenticate() 返回的是一个元组:

  1. user_auth_tuple = return (token_obj.user, token_obj)
  2. self.user, self.auth = (token_obj.user, token_obj)
  3. # 那么相当于,即将用户对象封装到 request 对象中,可以通过 request 访问用户相关信息:
  4. request.user = token_obj.user
  5. request.auth = token_obj

若没有返回值则执行 _not_authenticated() 方法,将返回一个匿名用户,认证失败:

  1. def _not_authenticated(self):
  2. """
  3. Set authenticator, user & authtoken representing an unauthenticated request.
  4. Defaults are None, AnonymousUser(匿名) & None.
  5. """
  6. self._authenticator = None
  7. if api_settings.UNAUTHENTICATED_USER:
  8. self.user = api_settings.UNAUTHENTICATED_USER()
  9. else:
  10. self.user = None
  11. if api_settings.UNAUTHENTICATED_TOKEN:
  12. self.auth = api_settings.UNAUTHENTICATED_TOKEN()
  13. else:
  14. self.auth = None

总结

通过一系列的认证,发现 rest framework 最终执行的是 authenticate() 方法来认证,如果在我们自定义认证类时,重写 authenticate() 方法,那么就默认会执行我们自己定义的 authenticate() 方法。


自定义认证类

app/utils/auth.py

通过获取 URL 中 token 来认证:

  1. from rest_framework import exceptions
  2. from app import models
  3. class MyAuthentication(object):
  4. def authenticate(self, request):
  5. token = request._request.GET.get('token')
  6. token_obj = models.UserToken.objects.filter(token=token).first()
  7. if not token_obj:
  8. raise exceptions.AuthenticationFailed('用户认证失败')
  9. return (token_obj.user, token_obj)
  10. def authenticate_header(self, val):
  11. pass

四、配置文件

1、在封装原生 request 对象的时候,我们发现 api_settings 是从 settings 中读取的配置文件:

  1. class APIView(View):
  2. # The following policies may be set at either globally, or per-view.
  3. renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
  4. parser_classes = api_settings.DEFAULT_PARSER_CLASSES
  5. authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

2、api_settings

从 settings 中加载 REST_FRAMEWORK,从而找到 DEFAULT_AUTHENTICATION_CLASSES

  1. api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
  2. def reload_api_settings(*args, **kwargs):
  3. setting = kwargs['setting']
  4. # 从 settings 中加载 REST_FRAMEWORK
  5. if setting == 'REST_FRAMEWORK':
  6. api_settings.reload()

3、基于此我们在 settings 中配置认证类,从而使得每个视图类都有认证功能,而不需要单独添加 authentication_classes = [MyAuthentication, ]

  1. # 设置全局认证
  2. REST_FRAMEWORK = {
  3. "DEFAULT_AUTHENTICATION_CLASSES": ['app.utils.auth.MyAuthentication', ] # 认证类的路径
  4. }

**如果某个视图类不需要认证,可以单独设置 authentication_classes = []**

五、其它内置认证类

rest framework 还提供了一些其他的内置认证类 rest_framework/authentication.py

类 BaseAuthentication

BaseAuthentication 就实现了两个方法,因此我们自定义认证类时继承 BaseAuthentication 可以不写 authenticate_header() 方法,但是一定要重写 authenticate() 方法,否则会报错。

  1. class BaseAuthentication(object):
  2. """
  3. All authentication classes should extend BaseAuthentication.(所有的认证类都应该继承 BaseAuthentication)
  4. """
  5. def authenticate(self, request):
  6. """
  7. Authenticate the request and return a two-tuple of (user, token).
  8. """
  9. # 不重写会报错
  10. raise NotImplementedError(".authenticate() must be overridden.")
  11. def authenticate_header(self, request):
  12. """
  13. Return a string to be used as the value of the `WWW-Authenticate`
  14. header in a `401 Unauthenticated` response, or `None` if the
  15. authentication scheme should return `403 Permission Denied` responses.
  16. """
  17. pass

匿名用户

如果允许匿名用户(即没有登录的用户)访问,可以修改自定义认证类为 app/utils/auth.py

  1. from rest_framework import exceptions
  2. from app import models
  3. from rest_framework.authentication import BaseAuthentication
  4. class FirstAuthentication(BaseAuthentication):
  5. """不返回值,则会执行 _not_authenticated() 方法,返回一个匿名用户"""
  6. def authenticate(self, request):
  7. pass
  8. def authenticate_header(self, request):
  9. pass
  10. class MyAuthentication(BaseAuthentication):
  11. def authenticate(self, request):
  12. token = request._request.GET.get('token')
  13. token_obj = models.UserToken.objects.filter(token=token).first()
  14. if not token_obj:
  15. raise exceptions.AuthenticationFailed('用户认证失败')
  16. return (token_obj.user, token_obj)
  17. def authenticate_header(self, val):
  18. pass

2、settings.py

  1. # 设置全局认证
  2. REST_FRAMEWORK = {
  3. "DEFAULT_AUTHENTICATION_CLASSES": ['app.utils.auth.FirstAuthentication', 'app.utils.auth.MyAuthentication', ],
  4. }

访问:http 时首先会以 `` 认证,将返回一个匿名用户 AnonymousUser,当然你也可以设置为中文:

  1. # 设置全局认证
  2. REST_FRAMEWORK = {
  3. "DEFAULT_AUTHENTICATION_CLASSES": ['app.utils.auth.FirstAuthentication', 'app.utils.auth.MyAuthentication', ],
  4. "UNAUTHENTICATED_USER": lambda: '匿名用户'
  5. }

你也可设置为 None,Token 也可以设置:

  1. "UNAUTHENTICATED_TOKEN": None

总结

自定义认证类需要实现以下几步:

  • 自定义一个类,继承 BaseAuthentication,类中必须实现 authenticate() 方法
  • 若全局需要认证,配置 settings 即可
  • 若局部某个类视图不需要认证,可以在其中添加 authentication_classes = []
  • 若匿名用户也允许访问,可以定义一个类,不返回值

rest framework 认证的更多相关文章

  1. Django Rest Framework(认证、权限、限制访问频率)

    阅读原文Django Rest Framework(认证.权限.限制访问频率) django_rest_framework doc django_redis cache doc

  2. 04 Django REST Framework 认证、权限和限制

    目前,我们的API对谁可以编辑或删除代码段没有任何限制.我们希望有更高级的行为,以确保: 代码片段始终与创建者相关联. 只有通过身份验证的用户可以创建片段. 只有代码片段的创建者可以更新或删除它. 未 ...

  3. rest framework 认证 权限 频率

    认证组件 发生位置 APIview 类种的 dispatch 方法执行到 initial 方法 进行 认证组件认证 源码位置 rest_framework.authentication  源码内部需要 ...

  4. rest framework认证组件和django自带csrf组件区别详解

    使用 Django 中的 csrf 处理 Django中有一个django.middleware.csrf.CsrfViewMiddleware中间件提供了全局的csrf检查.它的原理是在<fo ...

  5. Django REST Framework 认证 - 权限 - 限制

    一. 认证 (你是谁?) REST framework 提供了一些开箱即用的身份验证方案,并且还允许你实现自定义方案. 自定义Token认证 第一步 : 建表>>>> 定义一个 ...

  6. Django REST framework认证权限和限制和频率

    认证.权限和限制 身份验证是将传入请求与一组标识凭据(例如请求来自的用户或其签名的令牌)相关联的机制.然后 权限 和 限制 组件决定是否拒绝这个请求. 简单来说就是: 认证确定了你是谁 权限确定你能不 ...

  7. restful framework 认证源码流程

    一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...

  8. Django后端项目----restful framework 认证源码流程

    一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...

  9. Rest Framework 认证源码流程

    一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...

随机推荐

  1. 如何使用RadioGroup和RadioButton实现FragmentTabHost导航效果?

    目录: 一.概述 最近在做一个新闻类结合社区的APP的时候,需要添加一个侧滑菜单的效果,考虑到可以使用DrawerLayout布局,但是问题是使用了 DrawerLayout布局后,主页内容应该是一个 ...

  2. BCH硬分叉在即,Bitcoin ABC和NChain两大阵营PK

    混迹币圈,我们都知道,BTC分叉有了BCH,而近期BCH也将面临分叉,这次分叉将是Bitcoin ABC和NChain两大阵营的较量,最后谁能成为主导,我们拭目以待. 比特币现金(BCH)的价格自上周 ...

  3. wifi androd 整体框架

    1. http://blog.csdn.net/myarrow/article/details/8129607/ 2.  http://blog.csdn.net/liuhaomatou/articl ...

  4. web 全栈 学习 2 一个好的页面是如何炼成的

    第一章:Web页面内容的构成2.Web内容的分工一个Web页面可能的构成(视觉上看):①文字.链接.标题②交互入口(表单元素)③图片(哪些类型)④动画 Flash动画 HTML5 CSS3 动画⑤音视 ...

  5. margin的相关属性及应用

    1.margin常见问题: ①IE6下双边距   (不推荐使用float+margin,可用padding替代) 详见<css浏览器兼容问题集锦>之4.IE6中margin双边距 ②IE6 ...

  6. ios浮层滑动不流畅解决方案

    前段时间做了一个浮层,但在ios上,浮层滑动不流畅,基本上是随着手指的移动而移动,经研究加上-webkit-overflow-scrolling: touch即可 eg: <!DOCTYPE h ...

  7. POJ 1330 Nearest Common Ancestors 【最近公共祖先LCA算法+Tarjan离线算法】

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 20715   Accept ...

  8. HDU3336 Count the string —— KMP next数组

    题目链接:https://vjudge.net/problem/HDU-3336 Count the string Time Limit: 2000/1000 MS (Java/Others)     ...

  9. 51Nod 1225 余数之和 —— 分区枚举

    题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1225 1225 余数之和  基准时间限制:1 秒 空间限制:1 ...

  10. nginx.config配置文件模板

    #user nobody;worker_processes 1; #error_log logs/error.log;#error_log logs/error.log notice;#error_l ...