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


Posted in Python onAugust 06, 2019

一.前提

首先是这个代码基于前后端分离的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的函数都放在里面,后面要用到,都调用这个模块

django基于存储在前端的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认证功能

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

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请求:

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

返回结果:

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

访问get请求:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现数通设备端口使用情况监控实例
Jul 15 Python
Python实现对excel文件列表值进行统计的方法
Jul 25 Python
使用Python生成随机密码的示例分享
Feb 18 Python
EM算法的python实现的方法步骤
Jan 02 Python
学习Python selenium自动化网页抓取器
Jan 20 Python
Python实现PS图像调整黑白效果示例
Jan 25 Python
python requests post多层字典的方法
Dec 27 Python
python实现公司年会抽奖程序
Jan 22 Python
python+django+rest框架配置创建方法
Aug 31 Python
Window10下python3.7 安装与卸载教程图解
Sep 30 Python
使用 Python 读取电子表格中的数据实例详解
Apr 17 Python
tensorflow中的数据类型dtype用法说明
May 26 Python
django基于cors解决跨域请求问题详解
Aug 06 #Python
django组合搜索实现过程详解(附代码)
Aug 06 #Python
使用Python自动生成HTML的方法示例
Aug 06 #Python
Django RBAC权限管理设计过程详解
Aug 06 #Python
python虚拟环境完美部署教程
Aug 06 #Python
python批量图片处理简单示例
Aug 06 #Python
Python实用库 PrettyTable 学习笔记
Aug 06 #Python
You might like
模仿OSO的论坛(四)
2006/10/09 PHP
微信营销平台系统?刮刮乐的开发
2014/06/10 PHP
PHP文件生成的图片无法使用CDN缓存的解决方法
2015/06/20 PHP
新页面打开实际尺寸的图片
2006/08/25 Javascript
解放web程序员的输入验证
2006/10/06 Javascript
javaScript年份下拉列表框内容为当前年份及前后50年
2014/05/28 Javascript
javascript中实现兼容JAVA的hashCode算法代码分享
2020/08/11 Javascript
js实现可兼容IE、FF、Chrome、Opera及Safari的音乐播放器
2015/02/11 Javascript
利用jsonp跨域调用百度js实现搜索框智能提示
2016/08/24 Javascript
javascript实现将数字转成千分位的方法小结【5种方式】
2016/12/11 Javascript
javascript 中null和undefined区分和比较
2017/04/19 Javascript
Websocket 向指定用户发消息的方法
2020/01/09 Javascript
javascript实现计算器功能
2020/03/30 Javascript
python实现判断数组是否包含指定元素的方法
2015/07/15 Python
python实现简单爬虫功能的示例
2016/10/24 Python
Python实现连接postgresql数据库的方法分析
2017/12/27 Python
python使用tensorflow保存、加载和使用模型的方法
2018/01/31 Python
python实现对指定输入的字符串逆序输出的6种方法
2018/04/26 Python
Python基于sklearn库的分类算法简单应用示例
2018/07/09 Python
详解利用Python scipy.signal.filtfilt() 实现信号滤波
2019/06/05 Python
python binascii 进制转换实例
2019/06/12 Python
Python将视频或者动态图gif逐帧保存为图片的方法
2019/09/10 Python
python微信公众号开发简单流程实现
2020/03/09 Python
新西兰最大的连锁超市:Countdown
2020/06/04 全球购物
求高于平均分的学生学号及成绩
2016/09/01 面试题
寒假思想汇报
2014/01/10 职场文书
最新奶茶店创业计划书
2014/01/25 职场文书
2014年两会学习心得体会
2014/03/10 职场文书
小学数学教研活动总结
2014/07/01 职场文书
煤矿开采专业求职信
2014/07/08 职场文书
活动总结新闻稿
2014/08/30 职场文书
实施意见格式范本
2015/06/05 职场文书
2015年除四害工作总结
2015/07/23 职场文书
公安忠诚教育心得体会
2016/01/23 职场文书
2016年小学中秋节活动总结
2016/04/05 职场文书
使用CSS连接数据库的方式
2022/02/28 HTML / CSS