Fastapi token検証


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)