首先,安装需要的Python库:
pip install fastapi uvicorn python-jose[cryptography] passlib[bcrypt]
接下来,我们将创建一个名为main.py
的文件,其中包含我们的FastAPI应用程序。
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from datetime import datetime, timedelta
from jose import JWTError, jwt
# 定义密码上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# 构建FastAPI应用程序
app = FastAPI()
# 定义身份验证对象
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# 定义一些常量
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
SECRET_KEY = "1b539c7abb9826f02f13c7d4a098bd87e281e0bdf90d1c4eef4f3f4a11a30"
# 模拟数据库中的用户,实际项目中需要更加安全的存储方式
fake_users_db = {
"john@example.com": {
"username": "john@example.com",
"full_name": "John Doe",
"email": "john@example.com",
"hashed_password": "$2b$12$rPjn6vzoo6DU.OUcv9KjW.5BbgvFRwD.N5py5Q/N8WqptRe2JM1Sm",
"disabled": False,
"role": "admin"
},
"jane@example.com": {
"username": "jane@example.com",
"full_name": "Jane Doe",
"email": "jane@example.com",
"hashed_password": "$2b$12$faOYc9X8NsjWfOsNtvw5suDws5lwQ8xdTLuV7f/vKj/Gu.7JXbzIu",
"disabled": True,
"role": "user"
}
}
# 定义用户模型
class User(BaseModel):
username: str
full_name: str = None
email: str = None
disabled: bool = None
role: str = None
# 定义用户验证函数
def fake_hashed_password(password: str):
return pwd_context.hash(password)
def fake_verify_password(plain_password: str, hashed_password: str):
return pwd_context.verify(plain_password, hashed_password)
def get_user(username: str):
if username in fake_users_db:
user_dict = fake_users_db[username]
return User(**user_dict)
def authenticate_user(username: str, password: str):
user = get_user(username)
if not user:
return False
if not fake_verify_password(password, user.hashed_password):
return False
return user
# 定义创建访问令牌函数
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=401, detail="Invalid authentication credentials")
except JWTError:
raise HTTPException(status_code=401, detail="Invalid authentication credentials")
user = get_user(username)
if user is None:
raise HTTPException(status_code=401, detail="Invalid authentication credentials")
return user
# 定义验证管理员权限函数
async def get_current_admin_user(current_user: User = Depends(get_current_user)):
if current_user.role != "admin":
raise HTTPException(status_code=403, detail="You don't have admin privileges")
return current_user
# 定义登录路由
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect email 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("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
# 定义只有管理员可以访问的路由
@app.get("/users/admin")
async def read_users_admin(current_user: User = Depends(get_current_admin_user)):
return {"users": fake_users_db}
以上示例代码构建了一个基本的用户登录API,并添加了管理员权限功能。以此为基础可以进行更多的开发并实现更复杂的需求。