要在FastAPI中使用JWT進行身份驗證,我們可以使用PyJWT庫來生成和驗證JWT令牌。以下是一個簡單的示例代碼,演示如何在FastAPI應用程序中使用JWT進行身份驗證:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
app = FastAPI()
# 加密算法
SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# 密碼加密
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# 用戶數據模型
users = {
"user1": {
"username": "user1",
"password": "$2b$12$4QaMelDZ6p8H7bVz5H3RAuRfWFd2cE4VAUZd0nJ9H6p9BTJp6kQF6", # 加密后的密碼為password
"disabled": False
}
}
# 生成JWT令牌
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
# 驗證JWT令牌
def decode_access_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
# 使用OAuth2PasswordBearer進行身份驗證
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# 身份驗證路由
@app.post("/token")
async def login(form_data: dict = Depends(oauth2_scheme)):
user = users.get(form_data["username"])
if user is None or not pwd_context.verify(form_data["password"], user["password"]):
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(data={"sub": user["username"]}, expires_delta=access_token_expires)
return {"access_token": access_token, "token_type": "Bearer"}
# 保護需要身份驗證的路由
@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
payload = decode_access_token(token)
username = payload.get("sub")
user = users.get(username)
if user is None:
raise HTTPException(status_code=400, detail="User not found")
return user
在上面的示例中,我們首先定義了一個create_access_token
函數來生成JWT令牌,然后定義了一個decode_access_token
函數來驗證JWT令牌。接著使用OAuth2PasswordBearer
類來創建一個OAuth2密碼驗證方案。然后我們定義了一個登錄路由/token
來驗證用戶的用戶名和密碼,并生成JWT令牌。最后我們定義了一個受保護的路由/protected
,使用Depends(oauth2_scheme)
來進行身份驗證。
請注意,以上示例僅作為演示目的,實際項目中可能需要根據需要進行更多的安全性配置和優化。