# FastAPI安全：400错误请求：用户名或密码不正确

- **ID:** `python/fastapi-oauth2-password-error`
- **领域:** python
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

OAuth2密码流程收到无效凭据，可能是因为用户不存在或密码哈希不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (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)
   ```
2. **** (90% 成功率)
   ```
   Check if the user exists first: user = db.query(User).filter(User.username == username).first()\nif not user:\n    raise HTTPException(400)
   ```

## 无效尝试

- **** — Storing plaintext passwords and comparing directly is insecure and may cause hash mismatches. (90% 失败率)
- **** — Using the wrong hashing algorithm (e.g., md5) can cause verification failures. (70% 失败率)
