JWT令牌身份验证不正确



我正在构建一个API,并尝试实现jwt令牌。

我有两段代码负责JWT的工作:

# Responsible for signinh, encoding, decoding and returning JWTs
JWT_SECRET = config("secret")
JWT_ALGORITHM = config("algorithm")
# This returns the generated tokens
def token_response(token: str):
return {
"access token": token
}
# This is used for signing the JWT string
def signJWT(userID: str) -> Dict[str, str]:
payload = {
"userID": userID,
"expiry": time.time() + 600
}
token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
return token_response(token)
def decodeJWT(token: str) -> dict:
try:
decode_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
return decode_token if decode_token['expires'] >= time.time() else None
except:
return {}

和:

class JWTBearer(HTTPBearer):
def __init__(self, auto_error: bool = True):
super(JWTBearer, self).__init__(auto_error=auto_error)
async def __call__(self, request: Request):
credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
if credentials:
if not credentials.scheme == "Bearer":
raise HTTPException(status_code=403, detail="Invalid authentication scheme.")
if not self.verify_jwt(credentials.credentials):
raise HTTPException(status_code=403, detail="Invalid token or expired token.")
return credentials.credentials
else:
raise HTTPException(status_code=403, **detail="Invalid authorization code."**)
def verify_jwt(self, jwtoken: str) -> bool:
isTokenValid: bool = False
try:
payload = decodeJWT(jwtoken)
except:
payload = None
if payload:
isTokenValid = True

return isTokenValid

有了这个,我可以生成令牌,但当我尝试验证它时,我会得到detail="Invalid token or expired token."

我似乎找不到它为什么不进行身份验证。当然,如果我从代码中删除"if",任何字符串都是有效的。。。所以我认为是围绕着这个部分。

简短回答

只需添加";Bearer";在标头中令牌之前的授权字符串中

回答稍长

授权标头应包含令牌AND授权方法。如果没有方法fastAPI,就不知道该如何处理此令牌。在您的情况下,授权方法是Bearer。这里的问题是,当头丢失auth.method时,fastAPI无法正常处理异常,并且给出了误导性的异常描述(在我的案例中,描述是"异常:没有描述"(

如果你想创建一个应用程序,应该连接到你的API授权,然后添加授权方法到标题:

requests.post(self.apiFullAddress+postfix, json=postData, headers={"Authorization": "Bearer " + self.accessTocken})

也适用于网络应用程序:

curl -X 'POST' 
'http://127.0.0.1:8000/' 
-H 'accept: application/json' 
-H 'Authorization: Bearer YoUr_ToKeN' 
-H 'Content-Type: application/json' 
-d '{
"data": "SomeData",
"moredata": "SomeMoreData"
}'

最新更新