Python FastAPI框架实现一个基本的用户登录接口,并添加权限功能

该代码示例展示了如何用FastAPI构建一个包含用户登录、JWT令牌生成和权限验证(包括管理员权限)的API应用。它使用了Python-jose库处理JWT,passlib库处理密码加密,并通过依赖注入实现用户身份验证。
摘要由CSDN通过智能技术生成

首先,安装需要的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,并添加了管理员权限功能。以此为基础可以进行更多的开发并实现更复杂的需求。

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值