当前位置:   article > 正文

Django-rest-framework 接口实现 认证:(auth | authentication)

django-restframework authentication.tokenauthentication

认证:(auth | authentication)

REST framework提供了一些开箱即用的身份验证方案,并且还允许你实现自定义方案。

rest_framework.authentication 中 查看 认真方案

方案的 基类from rest_framework.authentication import BaseAuthentication

  • 基于用户名密码的 认证
  • BasicAuthentication(BaseAuthentication)
  • 基于Session的认证
    • SessionAuthentication(BaseAuthentication)
  • 基于Token 的认证
    • TokenAuthentication(BaseAuthentication)
  • 基于远程用户的认证(专用用户管理服务器)
    • RemoteUserAuthentication(BaseAuthentication)
认证的流程

rest_framework 中的

  • 在APIView 的 dispatch() 方法 执行 了 和 普通djando 不一样的方法 self.initial(request,*,**) 方法 中 添加了新动作 (版本号的获取,认证,权限,频率限制)

    顺序 先认证 再权限 再限制

    认证

    self.perform_authentiction(request)

    权限

    self.check_permissions(request)

    限制

    self.check_throttles(request)

自定义认证 token
  • 创建一个APP 将所有的 版本控制 认证 权限 与 主业务 区分开

定义一个类继承 BaseAuthentication 基于Token的认证

注意:

  • 不做认证 就不会有 request.user 个人用户信息

  • 重写 authenticte() 方法 通过 request.query_params.get('token') 获取 token 参数
  • 通过认证必须返回两个参数 第一个是用户的 queryset 对象 第二个是token 值 元组的形式
  • 错误或异常 需要抛出 AuthenticationFailed 错误

  1. # 所有 认证 的 父类
  2. from rest_framework.authentication import BaseAuthentication
  3. from auth_demo import models
  4. # 不通过认证 需要抛出的 字段错误
  5. from rest_framework.exceptions import AuthenticationFailed
  6. class LoginAuth(BaseAuthentication):
  7. 重写父类的 authenticte 方法 认证信息携带在 params 路由参数中
  8. def authenticate(self, request):
  9. token = request.query_params.get('token')
  10. if token:
  11. # 如果请求的URL中携带了token参数
  12. user_obj = models.UserInfo.objects.filter(token=token).first()
  13. if user_obj:
  14. # token是有效的
  15. return user_obj, token # request.user, request.auth
  16. else:
  17. raise AuthenticationFailed('无效的token')
  18. else:
  19. raise AuthenticationFailed('请求的URL中必须携带token参数')

操作流程:

  1. 创建用户表 认证登录操作 最好额外创建APP

    1. from django.db import models
    2. class UserInfo(models.Model):
    3. name = models.CharField(max_length=32)
    4. pwd = models.CharField(max_length=32)
    5. # token 设置为可以为空 查询时可以为空的字段 有时注册了但没有登录
    6. token = models.CharField(max_length=128, null=True, blank=True)
  2. 创建 注册需要的 接口 127.0.0.1:8000/user/register/

    1. # 一级路由
    2. from django.conf.urls import url, include
    3. urlpatterns = [
    4. url(r'^users/', include('auth_demo.urls')),
    5. ]
    6. # 二级路由
    7. from django.conf.urls import url, include
    8. from auth_demo import views
    9. urlpatterns = [
    10. url(r'^register/$', views.RegisterView.as_View()),
    11. ]
  3. 创建注册的视图类 Register

    1. from rest_framework.views import APIView
    2. from rest_framework.response import Response
    3. from auth_demo import models
    4. class RegisterView(APIView):
    5. ''' 注册用户的试图 只提供 post 请求 '''
    6. def post(self, request):
    7. # 获取 用户名密码
    8. name, pwd = request.data.get('name'), request.data.get('pwd')
    9. # 可以做一些 账号密码的 限制
    10. if name and pwd:
    11. models.UserInfo.objects.create(name=name,pwd=pwd)
    12. return Response('创建成功')
    13. else:
    14. return Response('无效的参数')
  4. 登录之后使用uuid.uuid1().hex生成token 保存到数据库中

    使用 update_or_create 方法 有就更新 没有就新增

    1. class LoginView(APIView):
    2. def post(self, request):
    3. name = request.data.get('name')
    4. pwd = request.data.get('pwd')
    5. if name and pwd:
    6. user_obj = models.UserInfo.objects.filter(name=name, pwd=pwd).first()
    7. if user_obj:
    8. # 登陆成功
    9. # 生成token(时间戳 + Mac地址)
    10. token = uuid.uuid1().hex
    11. # 1.保存在用户表中
    12. user_obj.token = token
    13. user_obj.save()
    14. # 2.给用户返回
    15. return Response({'error_no': 0, 'token': token})
    16. else:
    17. # 用户名或密码错误 通过 error_no 来判断请求是否成功
    18. return Response({'error_no': 1, 'error': '用户名或密码错误'})
    19. else:
    20. return Response('无效的参数')
  5. 将认证的 类添加到 配置项中

    全局配置

    1. # 后面的 权限 是基于 认证的 所以全局一定要配置 权限
    2. REST_FRAMEWORK = {
    3. # 自定义的 认证
    4. # 'DEFAULT_AUTHENTICATION_CLASSES': ['auth_demo.auth.MyAuth', ],
    5. # 使用 rest_framework 给出的认证
    6. # 'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentiction.TokenAuthentication', ]
    7. # 限制比较宽松的认证
    8. 'DEFAULT_AUTHENTICTION_CLASSES': []
    9. }
    '
    运行

    局部配置

    1. # 写在单独的试图中
    2. authentication_classes = [MyAuth, ]

转载于:https://www.cnblogs.com/zhang-zi-yi/p/10447371.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/857035
推荐阅读
相关标签
  

闽ICP备14008679号