Fastapi token验证
服务端:
/security.py:
import hashlib
import hmac
from fastapi import HTTPException, Header
import time
SECRET = '123' # 秘钥串,自定义
def get_sign(username: str, nonce: str, ts: str, sk: str) -> str:
"""
生成签名
ak:也可以使用各自的id
nonce:随机值
ts:10位时间戳
sk:secret加密用
"""
a = [username, nonce, ts, sk]
a.sort()
# a = [self.ak, 'ZPMxNpPhmrPzQj27AGKijM3FmEcHW4BY', '1550032562']
join_str = "".join(a)
return hmac.new(sk.encode(), join_str.encode(), hashlib.sha256).hexdigest()
async def token_is_true(username: str = Header(..., ), nonce: str = Header(..., ), timestamp: str = Header(..., ),
token: str = Header(..., description="token验证")):
"""签名验证,全局使用,超过60秒或者验证失败就会报错"""
if time.time() - int(timestamp) > 60 or token == get_sign(username, nonce, timestamp, SECRET):
raise HTTPException(
status_code=401,
detail="token is fail",
headers={
"X-Error": "There goes my error"},
)
else:
return {
"server_id": username}
/api.py
@app.post('/ip/query')
def get_ip(data: Ip_Model, token: str = Depends(token_is_true)):
username = data.username
res = Database(username, 'query')
print('[{}]'.format(username), '查询余额', '[{}]'.format(res), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
return JSONResponse(content={
"code": 200, "data": '查询成功', "price": res})
客户端
import hashlib
import hmac
import random
import time
import requests
def get_sign(username: str, nonce: str, ts: str, sk: str) -> str:
"""
生成签名
ak:也可以使用各自的id
nonce:随机值
ts:10位时间戳
sk:secret加密用
"""
a = [username, nonce, ts, sk]
a.sort()
# a = [self.ak, 'ZPMxNpPhmrPzQj27AGKijM3FmEcHW4BY', '1550032562']
join_str = "".join(a)
return hmac.new(sk.encode(), join_str.encode(), hashlib.sha256).hexdigest()
sign = get_sign('123', str(random.random()), str(int(time.time())), '123')
print(sign)
header = {
'username': '123',
'nonce': str(random.random()),
'timestamp': str(int(time.time())),
# 'timestamp': str('1014648188'),
'token': sign
}
data= {
'username': 'sss'
}
res = requests.post('http://127.0.0.1:8080/ip/query', headers=header, json=data)
print(res.text)