基于FastAPI的用户认证和登录接口实现,提供JWT令牌认证功能。
.
├── app/
│ ├── __init__.py # Python包初始化文件
│ ├── main.py # FastAPI主应用文件
│ ├── config.py # 应用配置管理
│ ├── database.py # 数据库配置和连接
│ ├── models.py # SQLAlchemy数据模型
│ ├── schemas.py # Pydantic数据模式
│ ├── crud.py # 数据库CRUD操作
│ ├── auth.py # 认证工具函数
│ └── dependencies.py # FastAPI依赖注入
├── .env # 环境变量配置文件
├── Pipfile # Pipenv依赖管理文件
└── README.md # 项目说明文档
- ✅ 用户认证和JWT令牌生成
- ✅ 密码哈希加密存储
- ✅ Bearer Token认证
- ✅ 用户信息获取接口
- ✅ 数据库模型和CRUD操作
- ✅ 环境变量配置管理
- ✅ API文档自动生成
- FastAPI: 现代、快速的Web框架
- SQLAlchemy: Python SQL工具包和ORM
- PostgreSQL: 关系型数据库
- PassLib: 密码哈希库
- python-jose: JWT令牌处理
- Pydantic: 数据验证和设置管理
- Uvicorn: ASGI服务器
# 安装pipenv(如果尚未安装)
pip install pipenv
# 安装项目依赖
pipenv install
# 激活虚拟环境
pipenv shell
确保 .env
文件中的数据库连接信息正确:
DATABASE_URL=postgresql://username:password@localhost/dbname
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# 使用uvicorn启动开发服务器
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# 或者直接运行main.py
python -m app.main
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
用户登录接口,返回JWT访问令牌。
请求体:
{
"username": "user@example.com",
"password": "yourpassword"
}
响应:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}
获取当前用户信息接口(需要认证)。
请求头:
Authorization: Bearer <access_token>
响应:
{
"id": 1,
"email": "user@example.com",
"is_active": true
}
创建新用户接口。
请求体:
{
"email": "newuser@example.com",
"password": "strongpassword123"
}
curl -X POST "http://localhost:8000/users/" \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "testpassword123"
}'
curl -X POST "http://localhost:8000/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=test@example.com&password=testpassword123"
curl -X POST "http://localhost:8000/users/me" \
-H "Authorization: Bearer <your_access_token>"
- 数据库表会在应用启动时自动创建
- JWT令牌默认30分钟过期
- 密码使用bcrypt算法加密
- 所有API端点都有详细的文档和类型注解
- 请确保在生产环境中使用强密钥
- 定期更新依赖包版本
- 配置适当的CORS策略
- 使用HTTPS协议传输敏感数据