網(wǎng)站程序在后端api接口中移動(dòng)端通過訪問url來獲取參數(shù),就在這種獲取url參數(shù)的時(shí)候如果接口不進(jìn)行加密驗(yàn)證,那么很有可能會(huì)造成數(shù)據(jù)泄露,本文便是為解決django開發(fā)api接口驗(yàn)證的問題。
首先需要安裝itsdangerous模塊 利用pip install itsdangerous 自動(dòng)安裝
然后導(dǎo)入該包
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import itsdangerous,time
然后程序中設(shè)置兩串加密字符串(key,salt隨意設(shè)置)和過期時(shí)間
secret_key = "" #key
salt_str = "" #salt
expires_in = 60 #過期時(shí)間
獲取token:
s = Serializer(secret_key=secret_key, expires_in=expires_in, salt=salt_str, )
token = s.dumps({
"uid": 1,
"type": 1,
"iat": time.time(),
}).decode("utf-8") #填寫后面想要token解析出的參數(shù)
解析token:
def parser_token(token):
s = Serializer(secret_key=secret_key,expires_in=expires_in,salt=salt_str)
try:
return {"msg":"解析成功","code":1,"data":s.loads(token)}
except itsdangerous.SignatureExpired:
return {"msg":"token已過期請(qǐng)重新登錄","code":-1}
except itsdangerous.BadSignature as e:
if e.payload:
try:
s = s.load_payload(e.payload)
print(s)
return {"msg": "secret_key 和 salt可能已經(jīng)泄露", "code": -1}
except:pass
return {"msg": "token被篡改", "code": -1}
except:
return {"msg": "解析失敗 未知原因!", "code": -1}
設(shè)計(jì)程序時(shí)可以在會(huì)員登錄的時(shí)候?qū)oken頒發(fā)出去,然后在后面所有接口的header中都添加上token字段,這樣便能達(dá)到token驗(yàn)證的目的,保護(hù)數(shù)據(jù)安全。例: