fastapi token 如何实现token有效时长更新
要实现FastAPI token有效时长更新,可以使用以下步骤:
- 在创建token时,添加一个
expires_delta参数,用于设置token的有效时长,例如:
from datetime import timedelta
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
- 在验证token时,检查token是否过期,并且如果token即将过期,则更新token的有效时长,并返回新的token,例如:
from datetime import datetime, timedelta
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# check if token is about to expire
expire_time = datetime.fromtimestamp(payload['exp'])
remaining_time = expire_time - datetime.utcnow()
if remaining_time < timedelta(minutes=5): # if token expires in less than 5 minutes
new_token = create_access_token(data={"sub": username}, expires_delta=timedelta(minutes=30))
return (username, new_token)
else:
return (username, token)
在get_current_user函数中,通过jwt.decode方法解码token,并检查token是否过期。如果token即将过期,则使用create_access_token方法创建一个新的token,并返回新的token和用户名。否则,返回原始的token和用户名。在调用get_current_user函数时,可以使用Depends(get_current_user)来获取当前用户和token。
这样,就可以实现FastAPI token有效时长的更新。
原文地址: https://www.cveoy.top/t/topic/bJlz 著作权归作者所有。请勿转载和采集!