python auth_error ai_generated true

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

fastapi.security.OAuth2PasswordRequestForm: 400 Bad Request: Incorrect username or password

ID: python/fastapi-oauth2-password-error

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  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)

无效尝试

常见但无效的做法:

  1. 90% 失败

    Storing plaintext passwords and comparing directly is insecure and may cause hash mismatches.

  2. 70% 失败

    Using the wrong hashing algorithm (e.g., md5) can cause verification failures.