python
auth_error
ai_generated
true
FastAPI安全:400错误请求:用户名或密码不正确
fastapi.security.OAuth2PasswordRequestForm: 400 Bad Request: Incorrect username or password
ID: python/fastapi-oauth2-password-error
80%修复率
84%置信度
0证据数
2024-04-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
OAuth2密码流程收到无效凭据,可能是因为用户不存在或密码哈希不匹配。
English
The OAuth2 password flow receives invalid credentials, either because the user doesn't exist or the password hash doesn't match.
解决方案
-
95% 成功率
Use passlib and bcrypt: from passlib.context import CryptContext\npwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')\nif not pwd_context.verify(password, user.hashed_password):\n raise HTTPException(400)
-
90% 成功率
Check if the user exists first: user = db.query(User).filter(User.username == username).first()\nif not user:\n raise HTTPException(400)
无效尝试
常见但无效的做法:
-
90% 失败
Storing plaintext passwords and comparing directly is insecure and may cause hash mismatches.
-
70% 失败
Using the wrong hashing algorithm (e.g., md5) can cause verification failures.