# Python OAuth2 认证服务器 这是一个用 Flask 编写的 OAuth2 认证服务器,实现了与 Node.js 版本相同的功能。 ## 功能特性 - ✅ OAuth2 认证流程 - ✅ HMAC-SHA256 签名验证 - ✅ Timing-safe 比较防止时序攻击 - ✅ 支持 Shopify OAuth 集成 - ✅ CORS 跨域支持 - ✅ 环境变量配置 ## 快速开始 ### 1. 安装依赖 ```bash pip install -r requirements.txt ``` ### 2. 运行服务器 ```bash python main.py ``` 服务器将在 `http://localhost:4000` 运行 ## API 端点 ### 1. 启动 OAuth 认证 ``` GET /api/auth?shop=example.myshopify.com ``` 重定向用户到 Shopify 授权页面。 ### 2. OAuth 回调处理 ``` GET /api/auth/callback?code=xxx&hmac=xxx&state=xxx&shop=example.myshopify.com ``` - 验证 HMAC 签名 - 交换授权码获取访问令牌 - 返回令牌信息 ## 项目结构 ``` python-app-demo/ ├── main.py # 主应用文件 ├── requirements.txt # Python 依赖 ├── .env # 环境变量(需要自己创建) └── README.md # 说明文档 ``` ## 与 Node.js 版本的对应关系 | Node.js (devServer) | Python (python-app-demo) | |-------------------|----------------------| | Express 服务器 | Flask 服务器 | | hmacValidatorMiddleWare | @hmac_validator 装饰器 | | secureCompare | secure_compare 函数 | | crypto.timingSafeEqual | hmac.compare_digest | | /api/auth | /api/auth 路由 | | /api/auth/callback | /api/auth/callback 路由 | ## 安全特性 1. **HMAC-SHA256 验证**:所有回调请求都通过 HMAC 签名验证 2. **Timing-safe 比较**:使用 `hmac.compare_digest` 防止时序攻击 3. **环境变量管理**:敏感配置存储在 `.env` 文件中 4. **CORS 支持**:安全的跨域资源共享 ## 使用 curl 测试 ```bash # 测试认证端点 curl "http://localhost:4000/api/auth?shop=example.myshopify.com" # 测试回调端点(需要有效的HMAC) curl "http://localhost:4000/api/auth/callback?code=test&hmac=xxx&state=xxx&shop=example.myshopify.com" ``` ## 完成! 现在您有一个完整的 Python OAuth2 认证服务器,功能与 Node.js 版本完全相同。🚀