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的函数都放在里面,后面要用到,都调用这个模块

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

以上是 django基于存储在前端的token用户认证解析 的全部内容, 来源链接: utcz.com/z/349472.html

回到顶部