博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django REST Framework自定义token认证
阅读量:4579 次
发布时间:2019-06-08

本文共 8717 字,大约阅读时间需要 29 分钟。

目录

一:模块导入

  • 导入模块

    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 blockvar foo = 'bar';
python manage.py makemigrations zhylbwgpython 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 renderfrom django.http import JsonResponsefrom rest_framework.views import APIViewfrom zhylbwg.models.auth import auth_modelsfrom zhylbwg.views import md5from django.views import Viewfrom 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 modelsfrom django.http import JsonResponsefrom rest_framework import exceptionsfrom zhylbwg.models import loginModelsfrom 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 JsonResponsefrom rest_framework.views import APIViewfrom zhylbwg.util.authenticationSelf import AuthenticationSelfORDER_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_FRAMEWORKREST_FRAMEWORK = {
# 全局认证类不要放在views下 "DEFAULT_AUTHENTICATION_CLASSES":['zhylbwg.util.authenticationSelf.AuthenticationSelf',]}
  • 局部配置–在需要配置认证的视图中
// An highlighted blockauthentication_classes = [AuthenticationSelf,]    #添加局部认证
  • 全局配置下局部过滤 --在需要过滤认证的视图中
// An highlighted block'''        在配置了全局认证的情况下,可以使用authentication_classes = [] 表示该视图不进行认证    '''    authentication_classes = []

转载地址:http://yaqms.baihongyu.com/

你可能感兴趣的文章
自我介绍以及关于软件工程的问题
查看>>
struts (一)
查看>>
【新番推荐】工作细胞
查看>>
NYOJ 16 矩形嵌套
查看>>
Leetcode中的SQL题目练习(二)
查看>>
dubbo 集群容错源码
查看>>
Collection接口的子接口——Queue接口
查看>>
LINUX安装NGINX
查看>>
服务器启动项目抛错 没有到主机的路由
查看>>
python_85_sys模块
查看>>
第九周动手动脑
查看>>
HDU 1811 Rank of Tetris
查看>>
网站UI分析
查看>>
winform 获取当前名称
查看>>
报表分栏后的排序
查看>>
Django中models定义的choices字典使用get_FooName_display()在页面中显示值
查看>>
nohup命令详解(转)
查看>>
别人的Linux私房菜(1)计算机概论
查看>>
系统编程之文件操作
查看>>
ModelState.IsValid
查看>>