概述
官方文档里面提供了使用jwt的方式进行的验证比较复杂,这里提供了一种原理相同,但是方式更简单的验证方式,一般更常见于开放api接口的时候的验证使用
全局依赖
创建一个文件存放全局依赖:
# depends.py
import hashlib
import hmac
from fastapi import HTTPException, Header
from settings import SECRET#秘钥串,是字符串
import time
def get_sign(ak: str, nonce: str, ts: str, sk: str)->str:
"""
生成签名
ak:也可以使用各自的id
nonce:随机值
ts:10位时间戳
sk:secret加密用
"""
# self.nonce = str(uuid.uuid1()).replace("-", "")
# nonce = str(uuid.uuid1()).replace("-", "")
a = [ak, nonce, ts]
a.sort()
# a = [self.ak, 'ZPMxNpPhmrPzQj27AGKijM3FmEcHW4BY', '1550032562']
join_str = "".join(a)
# print(join_str)
return hmac.new(sk.encode(), join_str.encode(), hashlib.sha256).hexdigest()
async def token_is_true(server_id: str = Header(..., ), nonce: str = Header(..., ), timestamp: str = Header(..., ),
token: str = Header(..., description="token验证")):
"""签名验证,全局使用,超过60秒或者验证失败就会报错"""
if time.time() - int(timestamp) > 60 or token == get_sign(server_id, nonce, timestamp, SECRET):
raise HTTPException(
status_code=401,
detail="token is fail",
headers={"X-Error": "There goes my error"},
)
else:
return {"server_id": server_id}#可以自定义返回值,比如user或者其他的数据
使用的时候,直接在变量增加即可:
@app.post("/test/")
async def test(token:str=Depends(token_is_true)):
"""测试代码"""
return {"code":0,"msg":"success"}