FastAPI认证系统:从零到令牌大师的奇幻之旅

完美体育365软件下载 📅 2026-01-08 08:54:06 ✍️ admin 👁️ 5061 ❤️ 677
FastAPI认证系统:从零到令牌大师的奇幻之旅

扫描二维码

关注或者微信搜一搜:编程智域 前端至全栈交流与成长

探索数千个预构建的 AI 应用,开启你的下一个伟大创意:https://tools.cmdragon.cn/

第一章:构建FastAPI完整认证系统1. 认证系统基础架构现代Web应用的认证系统通常包含以下核心组件:

用户注册模块(处理密码哈希存储)登录认证流程(JWT令牌颁发)权限验证中间件(保护API端点)令牌刷新机制(维护会话有效性)认证流程示意图:

客户端 → 注册 → 登录获取令牌 → 携带令牌访问API → 服务端验证令牌 → 返回资源

2. 完整实现步骤2.1 环境准备安装所需依赖(推荐使用虚拟环境):

pip install fastapi==0.78.0 uvicorn==0.18.2 python-jose[cryptography]==3.3.0 passlib[bcrypt]==1.7.4 python-multipart==0.0.52.2 数据库模型定义from pydantic import BaseModel, EmailStr

from typing import Optional

class UserCreate(BaseModel):

email: EmailStr

password: str

class UserInDB(UserCreate):

hashed_password: str

class Token(BaseModel):

access_token: str

token_type: str

class TokenData(BaseModel):

email: Optional[EmailStr] = None2.3 安全工具函数from datetime import datetime, timedelta

from jose import JWTError, jwt

from passlib.context import CryptContext

SECRET_KEY = "your-secret-key-here"

ALGORITHM = "HS256"

ACCESS_TOKEN_EXPIRE_MINUTES = 30

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain_password: str, hashed_password: str):

return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str):

return pwd_context.hash(password)

def create_access_token(data: dict):

to_encode = data.copy()

expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)

to_encode.update({"exp": expire})

return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)2.4 路由实现from fastapi import APIRouter, Depends, HTTPException, status

from fastapi.security import OAuth2PasswordRequestForm

router = APIRouter()

# 模拟数据库

fake_users_db = {}

@router.post("/register", response_model=UserInDB)

async def register(user: UserCreate):

if user.email in fake_users_db:

raise HTTPException(status_code=400, detail="Email already registered")

hashed_password = get_password_hash(user.password)

user_db = UserInDB(**user.dict(), hashed_password=hashed_password)

fake_users_db[user.email] = user_db.dict()

return user_db

@router.post("/login", response_model=Token)

async def login(form_data: OAuth2PasswordRequestForm = Depends()):

user_data = fake_users_db.get(form_data.username)

if not user_data or not verify_password(form_data.password, user_data["hashed_password"]):

raise HTTPException(

status_code=status.HTTP_401_UNAUTHORIZED,

detail="Invalid credentials",

headers={"WWW-Authenticate": "Bearer"},

)

access_token = create_access_token(data={"sub": user_data["email"]})

return {"access_token": access_token, "token_type": "bearer"}2.5 保护API端点from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")

async def get_current_user(token: str = Depends(oauth2_scheme)):

credentials_exception = HTTPException(

status_code=status.HTTP_401_UNAUTHORIZED,

detail="Could not validate credentials",

headers={"WWW-Authenticate": "Bearer"},

)

try:

payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])

email: str = payload.get("sub")

if email is None:

raise credentials_exception

except JWTError:

raise credentials_exception

user = fake_users_db.get(email)

if user is None:

raise credentials_exception

return user

@router.get("/protected")

async def protected_endpoint(current_user: UserInDB = Depends(get_current_user)):

return {

"message": f"Hello {current_user['email']}",

"protected_data": "Sensitive information here"

}3. 使用Swagger UI测试3.1 启动应用创建main.py:

from fastapi import FastAPI

app = FastAPI()

app.include_router(router, prefix="/api")

if __name__ == "__main__":

import uvicorn

uvicorn.run(app, host="0.0.0.0", port=8000)3.2 测试流程访问 http://localhost:8000/docs测试注册接口:请求体:{“email”: “[email protected]”, “password”: “secret”}测试登录接口获取令牌点击"Authorize"按钮,输入获取的JWT令牌测试/protected端点成功响应示例:

{

"message": "Hello [email protected]",

"protected_data": "Sensitive information here"

}4. 常见报错解决方案4.1 422 Validation Error现象:请求参数不符合验证规则解决方案:

检查请求体是否符合定义的Pydantic模型验证email格式是否正确(必须包含@符号)确保密码字段存在且长度合适4.2 401 Unauthorized原因:

缺失Authorization头令牌过期无效的签名

处理步骤:检查请求头是否包含Authorization: Bearer 重新获取有效令牌验证密钥和算法是否匹配课后QuizQ1:为什么在用户注册时要存储密码哈希而不是明文?A:防止数据库泄露导致用户密码暴露,哈希函数不可逆,提高系统安全性

Q2:JWT令牌包含哪三个主要组成部分?A:Header(元数据)、Payload(有效载荷)、Signature(签名验证)

Q3:如何实现自动刷新令牌?A:可以通过以下两种方式实现:

在令牌payload中添加refresh_token字段单独提供/refresh端点,使用长期有效的刷新令牌获取新的访问令牌Q4:访问/protected端点时出现403错误可能是什么原因?A:可能原因包括:

令牌已过期(超过30分钟)令牌签名与服务端密钥不匹配令牌中的用户信息不存在于数据库余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长,阅读完整的文章:

往期文章归档:FastAPI安全异常处理:从401到422的奇妙冒险 | cmdragon’s BlogFastAPI权限迷宫:RBAC与多层级依赖的魔法通关秘籍 | cmdragon’s BlogJWT令牌:从身份证到代码防伪的奇妙之旅 | cmdragon’s BlogFastAPI安全认证:从密码到令牌的魔法之旅 | cmdragon’s Blog密码哈希:Bcrypt的魔法与盐值的秘密 | cmdragon’s Blog用户认证的魔法配方:从模型设计到密码安全的奇幻之旅 | cmdragon’s BlogFastAPI安全门神:OAuth2PasswordBearer的奇妙冒险 | cmdragon’s BlogOAuth2密码模式:信任的甜蜜陷阱与安全指南 | cmdragon’s BlogAPI安全大揭秘:认证与授权的双面舞会 | cmdragon’s Blog异步日志监控:FastAPI与MongoDB的高效整合之道 | cmdragon’s BlogFastAPI与MongoDB分片集群:异步数据路由与聚合优化 | cmdragon’s BlogFastAPI与MongoDB Change Stream的实时数据交响曲 | cmdragon’s Blog地理空间索引:解锁日志分析中的位置智慧 | cmdragon’s Blog异步之舞:FastAPI与MongoDB的极致性能优化之旅 | cmdragon’s Blog异步日志分析:MongoDB与FastAPI的高效存储揭秘 | cmdragon’s BlogMongoDB索引优化的艺术:从基础原理到性能调优实战 | cmdragon’s Blog解锁FastAPI与MongoDB聚合管道的性能奥秘 | cmdragon’s Blog异步之舞:Motor驱动与MongoDB的CRUD交响曲 | cmdragon’s Blog异步之舞:FastAPI与MongoDB的深度协奏 | cmdragon’s Blog数据库迁移的艺术:FastAPI生产环境中的灰度发布与回滚策略 | cmdragon’s Blog数据库迁移的艺术:团队协作中的冲突预防与解决之道 | cmdragon’s Blog驾驭FastAPI多数据库:从读写分离到跨库事务的艺术 | cmdragon’s Blog数据库事务隔离与Alembic数据恢复的实战艺术 | cmdragon’s BlogFastAPI与Alembic:数据库迁移的隐秘艺术 | cmdragon’s Blog飞行中的引擎更换:生产环境数据库迁移的艺术与科学 | cmdragon’s BlogAlembic迁移脚本冲突的智能检测与优雅合并之道 | cmdragon’s Blog多数据库迁移的艺术:Alembic在复杂环境中的精妙应用 | cmdragon’s Blog数据库事务回滚:FastAPI中的存档与读档大法 | cmdragon’s BlogAlembic迁移脚本:让数据库变身时间旅行者 | cmdragon’s Blog数据库连接池:从银行柜台到代码世界的奇妙旅程 | cmdragon’s Blog点赞背后的技术大冒险:分布式事务与SAGA模式 | cmdragon’s BlogN+1查询:数据库性能的隐形杀手与终极拯救指南 | cmdragon’s BlogFastAPI与Tortoise-ORM开发的神奇之旅 | cmdragon’s BlogDDD分层设计与异步职责划分:让你的代码不再“异步”混乱 | cmdragon’s Blog异步数据库事务锁:电商库存扣减的防超卖秘籍 | cmdragon’s Blog免费好用的热门在线工具CMDragon 在线工具 - 高级AI工具箱与开发者套件 | 免费好用的在线工具应用商店 - 发现1000+提升效率与开发的AI工具和实用程序 | 免费好用的在线工具CMDragon 更新日志 - 最新更新、功能与改进 | 免费好用的在线工具支持我们 - 成为赞助者 | 免费好用的在线工具AI文本生成图像 - 应用商店 | 免费好用的在线工具临时邮箱 - 应用商店 | 免费好用的在线工具二维码解析器 - 应用商店 | 免费好用的在线工具文本转思维导图 - 应用商店 | 免费好用的在线工具正则表达式可视化工具 - 应用商店 | 免费好用的在线工具文件隐写工具 - 应用商店 | 免费好用的在线工具IPTV 频道探索器 - 应用商店 | 免费好用的在线工具快传 - 应用商店 | 免费好用的在线工具随机抽奖工具 - 应用商店 | 免费好用的在线工具动漫场景查找器 - 应用商店 | 免费好用的在线工具时间工具箱 - 应用商店 | 免费好用的在线工具网速测试 - 应用商店 | 免费好用的在线工具AI 智能抠图工具 - 应用商店 | 免费好用的在线工具背景替换工具 - 应用商店 | 免费好用的在线工具艺术二维码生成器 - 应用商店 | 免费好用的在线工具Open Graph 元标签生成器 - 应用商店 | 免费好用的在线工具图像对比工具 - 应用商店 | 免费好用的在线工具图片压缩专业版 - 应用商店 | 免费好用的在线工具密码生成器 - 应用商店 | 免费好用的在线工具SVG优化器 - 应用商店 | 免费好用的在线工具调色板生成器 - 应用商店 | 免费好用的在线工具在线节拍器 - 应用商店 | 免费好用的在线工具IP归属地查询 - 应用商店 | 免费好用的在线工具CSS网格布局生成器 - 应用商店 | 免费好用的在线工具邮箱验证工具 - 应用商店 | 免费好用的在线工具书法练习字帖 - 应用商店 | 免费好用的在线工具金融计算器套件 - 应用商店 | 免费好用的在线工具中国亲戚关系计算器 - 应用商店 | 免费好用的在线工具Protocol Buffer 工具箱 - 应用商店 | 免费好用的在线工具IP归属地查询 - 应用商店 | 免费好用的在线工具图片无损放大 - 应用商店 | 免费好用的在线工具文本比较工具 - 应用商店 | 免费好用的在线工具IP批量查询工具 - 应用商店 | 免费好用的在线工具域名查询工具 - 应用商店 | 免费好用的在线工具DNS工具箱 - 应用商店 | 免费好用的在线工具网站图标生成器 - 应用商店 | 免费好用的在线工具XML Sitemap

相关推荐

无缘世界杯,球迷下场群殴球员
365bet官网最新网址

无缘世界杯,球迷下场群殴球员

📅 09-21 👁️ 6164
撕人订制
完美体育365软件下载

撕人订制

📅 09-02 👁️ 3777
三星智能手机S22如何设置指纹锁?
365bet官网最新网址

三星智能手机S22如何设置指纹锁?

📅 10-20 👁️ 577