fastapi之token驗證

fastapi之token驗證

概述

官方文檔裏面提供了使用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"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章