django基于存储在前端的token用户认证

一.前提

首先是这个代码基于前后端分离的API,我们用了django的framework模块,帮助我们快速的编写restful规则的接口

前端token原理:

把(token=加密后的字符串,key=name)在登入后发到客户端,以后客户端再发请求,会携带过来服务端截取(token=加密后的字符串,key=name),我们再利用解密方法,将token和key进行解码,然后进行比对,成功就是登入过的认证,失败就是没有登入过的

还有一种方式,把{name:maple,id:1} 用我自己知道的加密方式加密之后变成了:加密字符串,加密字符串|{name:maple,id:1} 当做token,发到客户端,以后客户端再发请求,会携带,加密字符串|{name:maple,id:1}过来,服务端截取{name:maple,id:1},再用我们的加密方式加密:加密字符串,拿到加密后的字符串进行比对,这种方式,只要写一个密码函数就可以了,无需写解密函数

二.token加密与解密

在django的app中定义个token模块

将有关token的函数都放在里面,后面要用到,都调用这个模块
1493082-20190805111631656-1748811893.png

加密token函数:

import time
import base64
import hmacdef get_token(key, expire=3600):''':param key: str (用户给定的key,需要用户保存以便之后验证token,每次产生token时的key 都可以是同一个key):param expire: int(最大有效时间,单位为s):return: token'''ts_str = str(time.time() + expire)ts_byte = ts_str.encode("utf-8")sha1_tshexstr  = hmac.new(key.encode("utf-8"),ts_byte,'sha1').hexdigest()token = ts_str+':'+sha1_tshexstrb64_token = base64.urlsafe_b64encode(token.encode("utf-8"))return b64_token.decode("utf-8")

解密函数:

def out_token(key, token):''':param key: 服务器给的固定key:param token: 前端传过来的token:return: true,false'''# token是前端传过来的token字符串try:token_str = base64.urlsafe_b64decode(token).decode('utf-8')token_list = token_str.split(':')if len(token_list) != 2:return Falsets_str = token_list[0]if float(ts_str) < time.time():# token expiredreturn Falseknown_sha1_tsstr = token_list[1]sha1 = hmac.new(key.encode("utf-8"),ts_str.encode('utf-8'),'sha1')calc_sha1_tsstr = sha1.hexdigest()if calc_sha1_tsstr != known_sha1_tsstr:# token certification failedreturn False# token certification successreturn Trueexcept Exception as e:print(e)

三、视图CBV

登入函数:

from rest_framework.response import Response
from rest_framework.views import APIView
from app01 import models
# get_token生成加密token,out_token解密token
from app01.token_module import get_token,out_tokenclass AuthLogin(APIView):def post(self,request):response={"status":100,"msg":None}name=request.data.get("name")pwd=request.data.get("pwd")print(name,pwd)user = auth.authenticate(username=name, password=pwd)# user=models.User.objects.filter(username=name,password=pwd).first()if user:# token=get_random(name)# 将name进行加密,3600设定超时时间token=get_token(name,60)models.UserToken.objects.update_or_create(user=user,defaults={"token":token})response["msg"]="登入成功"response["token"]=tokenresponse["name"]=user.usernameelse:response["msg"]="用户名或密码错误"return Response(response)

登入后访问函数:

from rest_framework.views import APIView
from app01 import models
from app01.serialize_module import BookSerialize
from app01.authentication_module import TokenAuth1,TokenAuth2class Books(APIView):authentication_classes = [TokenAuth2]def get(self,request):response = {"status": 100, "msg": None}book_list=models.Book.objects.all()book_ser = BookSerialize(book_list, many=True)response["books"]=book_ser.datareturn Response(response)

路由:

from django.conf.urls import url
from django.contrib import admin
from app01 import viewsurlpatterns = [url(r'^admin/', admin.site.urls),url(r'^books/$', views.Books.as_view()),url(r'^login/$', views.AuthLogin.as_view()),
]

framework认证功能

1493082-20190805131646930-1721266787.png

from rest_framework.authentication import BaseAuthentication
from app01 import models
from rest_framework.exceptions import NotAuthenticated
# get_token生成加密token,out_token解密token
from app01.token_module import get_token,out_token# 存储在前端的token解密比对
class TokenAuth2(BaseAuthentication):def authenticate(self,request):token=request.GET.get("token")name=request.GET.get("name")token_obj=out_token(name,token)if token_obj:returnelse:raise NotAuthenticated("你没有登入")

利用postman软件在前端提交

登入POST请求:
1493082-20190805131801927-45069141.png
返回结果:
1493082-20190805131813333-796486209.png

访问get请求:
1493082-20190805131825278-2089521943.png

转载于:https://www.cnblogs.com/Paul-watermelon/p/11302449.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391882.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据分布策略_有效数据项目的三种策略

数据分布策略Many data science projects do not go into production, why is that? There is no doubt in my mind that data science is an efficient tool with impressive performances. However, a successful data project is also about effectiveness: doing the righ…

java基础学习——5、HashMap实现原理

一、HashMap的数据结构 数组的特点是&#xff1a;寻址容易&#xff0c;插入和删除困难&#xff1b;而链表的特点是&#xff1a;寻址困难&#xff0c;插入和删除容易。那么我们能不能综合两者的特性&#xff0c;做出一种寻址容易&#xff0c;插入删除也容易的数据结构&#xff1…

看懂nfl定理需要什么知识_NFL球队为什么不经常通过?

看懂nfl定理需要什么知识Debunking common NFL myths in an analytical study on the true value of passing the ball在关于传球真实价值的分析研究中揭穿NFL常见神话 Background背景 Analytics are not used enough in the NFL. In a league with an abundance of money, i…

29/07/2010 sunrise

** .. We can only appreciate the miracle of a sunrise if we have waited in the darkness .. 人们在黑暗中等待着&#xff0c;那是期盼着如同日出般的神迹出现 .. 附&#xff1a;27/07/2010 sunrise ** --- 31 July 改动转载于:https://www.cnblogs.com/orderedchaos/archi…

密度聚类dbscan_DBSCAN —基于密度的聚类方法的演练

密度聚类dbscanThe idea of having newer algorithms come into the picture doesn’t make the older ones ‘completely redundant’. British statistician, George E. P. Box had once quoted that, “All models are wrong, but some are useful”, meaning that no model…

嵌套路由

父组件不能用精准匹配&#xff0c;否则只组件路由无法展示 转载于:https://www.cnblogs.com/dianzan/p/11308146.html

从完整的新手到通过TensorFlow开发人员证书考试

I recently graduated with a bachelor’s degree in Civil Engineering and was all set to start with a Master’s degree in Transportation Engineering this fall. Unfortunately, my plans got pushed to the winter term because of COVID-19. So as of January this y…

【转】PHP面试题总结

PHP面试总结 PHP基础1&#xff1a;变量的传值与引用。 2&#xff1a;变量的类型转换和判断类型方法。 3&#xff1a;php运算符优先级&#xff0c;一般是写出运算符的运算结果。 4&#xff1a;PHP中函数传参&#xff0c;闭包&#xff0c;判断输出的echo&#xff0c;print是不是函…

移动平均线ma分析_使用动态移动平均线构建交互式库存量和价格分析图

移动平均线ma分析I decided to code out my own stock tracking chart despite a wide array of freely available tools that serve the same purpose. Why? Knowledge gain, it’s fun, and because I recognize that a simple project can generate many new ideas. Even t…

静态变数和非静态变数_统计资料:了解变数

静态变数和非静态变数Statistics 101: Understanding the different type of variables.统计101&#xff1a;了解变量的不同类型。 As we enter the latter part of the year 2020, it is safe to say that companies utilize data to assist in making business decisions. F…

Zabbix3.2安装

一、环境 OS: CentOS7.0.1406 Zabbix版本: Zabbix-3.2 下载地址: http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm MySQL版本: 5.6.37 MySQL: http://repo.mysql.com/mysql-community-release-el7-5.noarch.r…

Warensoft Unity3D通信库使用向导4-SQL SERVER访问组件使用说明

Warensoft Unity3D通信库使用向导4-SQL SERVER访问组件使用说明 (作者:warensoft,有问题请联系warensoft163.com) 在前一节《warensoft unity3d通信库使用向导3-建立WarensoftDataService》中已经说明如何配置Warensoft Data Service&#xff0c;从本节开始&#xff0c;将说明…

不知道输入何时停止_知道何时停止

不知道输入何时停止In predictive analytics, it can be a tricky thing to know when to stop.在预测分析中&#xff0c;知道何时停止可能是一件棘手的事情。 Unlike many of life’s activities, there’s no definitive finishing line, after which you can say “tick, I…

掌握大数据数据分析师吗?_要掌握您的数据吗? 这就是为什么您应该关心元数据的原因...

掌握大数据数据分析师吗?Either you are a data scientist, a data engineer, or someone enthusiastic about data, understanding your data is one thing you don’t want to overlook. We usually regard data as numbers, texts, or images, but data is more than that.…

docker在Centos上的安装

Centos6安装docker 系统&#xff1a;centos6.5 内核&#xff1a;3.10.107-1(已升级)&#xff0c;docker对RHEL/Centos的最低内核支持是2.6.32-431&#xff0c;epel源的docker版本推荐内核为3.10版本。 内核升级可参考&#xff1a;https://www.jslink.org/linux/centos-kernel-u…

Lambda表达式的前世今生

Lambda 表达式 早在 C# 1.0 时&#xff0c;C#中就引入了委托&#xff08;delegate&#xff09;类型的概念。通过使用这个类型&#xff0c;我们可以将函数作为参数进行传递。在某种意义上&#xff0c;委托可理解为一种托管的强类型的函数指针。 通常情况下&#xff0c;使用委托来…

matplotlib柱状图、面积图、直方图、散点图、极坐标图、箱型图

一、柱状图 1.通过obj.plot() 柱状图用bar表示&#xff0c;可通过obj.plot(kindbar)或者obj.plot.bar()生成&#xff1b;在柱状图中添加参数stackedTrue&#xff0c;会形成堆叠图。 fig,axes plt.subplots(2,2,figsize(10,6)) s pd.Series(np.random.randint(0,10,15),index …

微信支付商业版 结算周期_了解商业周期

微信支付商业版 结算周期Economics is an inexact science, finance and investing even more so (some would call them art). But if there’s one thing in economics that you can consistently count on over the long run, it’s the tendency of things to mean revert …

Bootstrap——可拖动模态框(Model)

还是上一个小项目&#xff0c;o(╥﹏╥)o&#xff0c;要实现点击一个div或者button或者一个东西然后可以弹出一个浮在最上面的弹框。网上找了找&#xff0c;发现Bootstrap的Model弹出框可以实现该功能&#xff0c;因此学习了一下&#xff0c;实现了基本弹框功能&#xff08;可拖…

mfcc中的fft操作_简化音频数据:FFT,STFT和MFCC

mfcc中的fft操作What we should know about sound. Sound is produced when there’s an object that vibrates and those vibrations determine the oscillation of air molecules which creates an alternation of air pressure and this high pressure alternated with low …