您好,登錄后才能下訂單哦!
首先是這個(gè)代碼基于前后端分離的API,我們用了django的framework模塊,幫助我們快速的編寫restful規(guī)則的接口
前端token原理:
把(token=加密后的字符串,key=name)在登入后發(fā)到客戶端,以后客戶端再發(fā)請(qǐng)求,會(huì)攜帶過來服務(wù)端截取(token=加密后的字符串,key=name),我們再利用解密方法,將token和key進(jìn)行解碼,然后進(jìn)行比對(duì),成功就是登入過的認(rèn)證,失敗就是沒有登入過的
還有一種方式,把{name:maple,id:1} 用我自己知道的加密方式加密之后變成了:加密字符串,加密字符串|{name:maple,id:1} 當(dāng)做token,發(fā)到客戶端,以后客戶端再發(fā)請(qǐng)求,會(huì)攜帶,加密字符串|{name:maple,id:1}過來,服務(wù)端截取{name:maple,id:1},再用我們的加密方式加密:加密字符串,拿到加密后的字符串進(jìn)行比對(duì),這種方式,只要寫一個(gè)密碼函數(shù)就可以了,無需寫解密函數(shù)
在django的app中定義個(gè)token模塊
將有關(guān)token的函數(shù)都放在里面,后面要用到,都調(diào)用這個(gè)模塊
加密token函數(shù):
import time import base64 import hmac def get_token(key, expire=3600): ''' :param key: str (用戶給定的key,需要用戶保存以便之后驗(yàn)證token,每次產(chǎn)生token時(shí)的key 都可以是同一個(gè)key) :param expire: int(最大有效時(shí)間,單位為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")
解密函數(shù):
def out_token(key, token): ''' :param key: 服務(wù)器給的固定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)
登入函數(shù):
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進(jìn)行加密,3600設(shè)定超時(shí)時(shí)間 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"]="用戶名或密碼錯(cuò)誤" return Response(response)
登入后訪問函數(shù):
from rest_framework.views import APIView from app01 import models from app01.serialize_module import BookSerialize from app01.authentication_module import TokenAuth2,TokenAuth3 class Books(APIView): authentication_classes = [TokenAuth3] 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()), ]
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 # 存儲(chǔ)在前端的token解密比對(duì) class TokenAuth3(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("你沒有登入")
登入POST請(qǐng)求:
返回結(jié)果:
訪問get請(qǐng)求:
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。