• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-07) 25次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了django基于存储在前端的token用户认证解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一.前提

首先是这个代码来源gao($daima.com搞@代@#码网基于前后端分离的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的函数都放在里面,后面要用到,都调用这个模块

加密token函数:

 import time import base64 import hmac def 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_tshexstr b64_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 False ts_str = token_list[0] if float(ts_str) <time.time(): # token expired return False known_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 failed return False # token certification success return True except 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_token class 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=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"]=token response["name"]=user.username else: 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,TokenAuth2 class 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.data return Response(response)

路由:

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

四.framework认证功能

 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: return else: raise NotAuthenticated("你没有登入")

五.利用postman软件在前端提交

登入POST请求:

返回结果:

访问get请求:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是django基于存储在前端的token用户认证解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:django基于存储在前端的token用户认证解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址