温馨提示×

FastAPI中怎么使用JWT进行身份验证

小亿
293
2024-05-10 16:38:17
栏目: 编程语言

要在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)来进行身份验证。

请注意,以上示例仅作为演示目的,实际项目中可能需要根据需要进行更多的安全性配置和优化。

0