Django REST Framework自定义token认证

一:模块导入

  • 导入模块

      pip install djangorestframeword  # 使用pip命令进行djangorestFramework
    
  • 配置,在setting.py中进行如下配置

在这里插入图片描述

二 :生成token

1:定义model,Userinfo和UserToken

from django.db import models
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:10/3/2020 下午2:14
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
class Userinfo(models.Model):
USER_TYPE = (
    (1, '普通用户'),
    (2, 'VIP'),
    (3, 'SVIP')
)
user_type = models.IntegerField(choices=USER_TYPE, blank=True, null=True)
userName = models.CharField(max_length=10)
userPwd = models.CharField(max_length=100)
userTelphone = models.CharField(max_length=10)
userAddress = models.CharField(max_length=10)
userAge = models.CharField(max_length=4)

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

2:执行数据迁移命令,生成表数据

// An highlighted block
var foo = 'bar';
python manage.py makemigrations zhylbwg
python manage.py migrate zhylbwg

3:用户注册

# -*- coding: utf-8 -*-
   '''===================================
   @Project:wisdomShop
   @Author:班婕妤
   @Date:5/3/2020 下午1:50
   @Company:深圳市智慧养老宝科技有限公司
   @Motto:心有猛虎,细嗅蔷薇
   @Python_Version:3.7.3
   @Django_Version:2.1.5
   ======================================='''
   from django.shortcuts import render,HttpResponse
   import pandas as pd
   import json
   from zhylbwg.models import loginModels
   from zhylbwg.views import md5  # 导入自定义md5加密函数
   from zhylbwg.views import requestResult  # 导入自定义的统一返回函数
	def register(request):
   # 判断是否为post请求
       if request.method == "POST":
           # 获取请求头数据,请求以json的格式传输
           registerinformation = request.body
           # 将请求头数据转化为json格式
           registerinformationData = json.loads(registerinformation)
           # 获取用户名
           userName = registerinformationData.get('userName')
           # 从数据库中查找是否存在该用户名
           userNameDB = loginModels.Userinfo.objects.filter(userName=userName)
           # 判断用户名是否存在,若存在,则提示已有该用户,若不存在,则进行密码加密后存储到数据库中
           if not userNameDB:
               return HttpResponse(json.dumps(requestResult.result_json('312', '该用户名已经存在', '')),
                                   content_type="application/json,charset=utf-8")
           else:
               # 获取用户密码
               #
               userPwd = registerinformationData.get('userPwd')
               # 密码加密操作md5,md5加密功能具体看md5加密代码
               userPwdMd5 = md5.Md5(userPwd)
               # 将加密后的密码赋值给请求头中的密码参数
               registerinformationData["userPwd"] = userPwdMd5
               # 将json格式数据,类型为dict 存储到数据库中,表明为Userinfo,将注册请求存储到数据库中
               loginModels.Userinfo.objects.create(**registerinformationData)
               return HttpResponse(json.dumps(requestResult.result_json('201', '注册成功,请登录', '')),
                                   content_type="application/json,charset=utf-8")
       else:
           return HttpResponse(json.dumps(requestResult.result_json('501', '不是post请求', '')),
                               content_type="application/json,charset=utf-8")
  • 测试注册接口
    在这里插入图片描述
  • 生成md5工具类
// An highlighted block
# -*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:5/3/2020 下午1:50
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
import hashlib  # 使用hashlib模块进行md5操作
def Md5(str):
  md5 = hashlib.md5()  # 创建md5对象
  # 此处必须声明encode
  # 若写法为hl.update(str)  报错为: Unicode-objects must be encoded before hashing
  md5.update(str.encode(encoding='utf-8'))
  # 把输入的旧密码装换为md5格式
  result = md5.hexdigest()
  # 返回加密结果
  return result
  • 返回统一json格式工具类
// An highlighted block
# -*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:5/3/2020 下午1:50
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
# 定义统一的json返回格式
def result_json(code, msg, data):
  # 创建一个空字典
  result = {"code": code, "msg": msg, "data": data}
  return result

4:根据用户名生成token

// An highlighted block
# -*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:10/3/2020 下午2:14
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from zhylbwg.models.auth import auth_models
from zhylbwg.views import md5
from django.views import View
from zhylbwg.models import loginModels
'''
    用户验证,当用户首次登录时随机生成一个token
'''
# CBV 视图模式
class AuthView(APIView):
    '''
        在配置了全局认证的情况下,可以使用authentication_classes = [] 表示该视图不进行认证
    '''
    authentication_classes = []
    def post(self, request):
        ret = {'code': 1000, 'msg': None}
        try:
            user = request.POST.get('username')
            pwd = md5.Md5(request.POST.get('password'))
            obj = loginModels.Userinfo.objects.filter(userName=user, userPwd=pwd).first()
            if not obj:
                ret['code'] = 1001
                ret['msg'] = '用户名或密码错误'
            # 为用户创建token
            token = md5.Md5(user)
            print(token)
            # 存在就更新,不存在就创建
            loginModels.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)

在这里插入图片描述

三:自定义认证类

1:自定义认证类

// An highlighted block
#-*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:10/3/2020 下午6:09
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
from django.db import models
from django.http import JsonResponse
from rest_framework import exceptions
from zhylbwg.models import loginModels
from rest_framework.authentication import BaseAuthentication
#################################################
#       自定义认证类路径不能放在                 #
#       views下,可单独建立目录存放              #
#################################################
'''
    自己写认证类方法梳理
    (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',]
        }
'''
class AuthenticationSelf(BaseAuthentication):
    '''认证'''
    def authenticate(self,request):
        print("========")
        print(request)
        token = request._request.GET.get('token')
        print(token)
        token_obj = loginModels.UserToken.objects.filter(token=token).first()
        print(token_obj)
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败-请申请认证')
        #在rest framework内部会将这两个字段赋值给request,以供后续操作使用
        return (token_obj.user,token_obj)

    def authenticate_header(self, request):
        pass

2:模拟一个订单视图

// An highlighted block
#-*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:10/3/2020 下午6:09
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
from django.http import JsonResponse
from rest_framework.views import APIView

from zhylbwg.util.authenticationSelf import AuthenticationSelf

ORDER_DICT = {
    1:{
        'name':'apple',
        'price':15
    },
    2:{
        'name':'dog',
        'price':100
    }
}
class OrderView(APIView):
    '''订单相关业务'''
    authentication_classes = [AuthenticationSelf,]    #添加局部认证
    def get(self,request,*args,**kwargs):
        ret = {'code':1000,'msg':None,'data':None}
        try:
            ret['data'] = ORDER_DICT
        except Exception as e:
            pass
        return JsonResponse(ret)

3:配置url

// An highlighted block
 path('zhylbwg/auth/', AuthView.as_view()),  # 生成token
 path('zhylbwg/authe/', OrderView.as_view()),  # 订单视图

4:测试接口

  • 未携带token
    在这里插入图片描述- 携带token
    在这里插入图片描述

四:认证配置

  • 全局配置–在settings.py中进行如下配置
// An highlighted block
# 配置全局认证 REST_FRAMEWORK
REST_FRAMEWORK = {
    # 全局认证类不要放在views下
    "DEFAULT_AUTHENTICATION_CLASSES":['zhylbwg.util.authenticationSelf.AuthenticationSelf',]
}
  • 局部配置–在需要配置认证的视图中
// An highlighted block
authentication_classes = [AuthenticationSelf,]    #添加局部认证
  • 全局配置下局部过滤 --在需要过滤认证的视图中
// An highlighted block
'''
        在配置了全局认证的情况下,可以使用authentication_classes = [] 表示该视图不进行认证
    '''
    authentication_classes = []
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

班婕妤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值