tiangolo/fastapi · error · HTTPException
Incorrect username or password
Error message
Incorrect username or password
What it means
The /token handler in the scopes tutorial raises HTTP 400 'Incorrect username or password' when authenticate_user is falsy. Note the status inconsistency: tutorial005 uses 400 here whereas tutorial004 used 401 — both share the same authenticate_user (with DUMMY_HASH timing protection) and the same anti-enumeration message.
Solutions
- POST username + password matching a seeded user (johndoe or alice with their original plaintext).
- If you changed the hasher, regenerate the stored argon2 hashes with get_password_hash.
- Standardize the status code on 401 with WWW-Authenticate for consistency with RFC 6749 and tutorial004.
Example fix
// before
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
// after
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}) Defensive patterns
Strategy: validation
Validate before calling
import httpx
def post_token(client: httpx.Client, u: str, p: str, scopes: str = ""):
assert u and p, "username/password required"
data = {"username": u, "password": p}
if scopes:
data["scope"] = scopes
return client.post("/token", data=data) Type guard
from typing import TypeGuard
def is_valid_creds(pair: tuple) -> TypeGuard[tuple[str, str]]:
u, p = pair
return isinstance(u, str) and isinstance(p, str) and u.strip() and p Try / catch
import httpx
try:
r = httpx.post("/token", data={"username": u, "password": p, "scope": "me items"})
r.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code in (400, 401):
show_generic_login_error() Prevention
- POST credentials form-encoded and request all needed scopes in the 'scope' field.
- Regenerate stored hashes when the hasher changes.
- Treat the credential error as final for those credentials.
When it happens
Trigger: POST /token (form-encoded) with username not in {johndoe, alice} or a password that fails argon2 verification. The form may also carry a scope field, but a credential failure short-circuits before scopes matter.
Common situations: Wrong password; missing username field; regenerated argon2 hashes; sending JSON instead of form data.
Related errors
AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11).
Data as JSON: /api/errors/8b5d2ffd48e1d414.
Report an issue: GitHub.
Appendix: source
Thrown at docs_src/security/tutorial005_an_py310.py:157
)
return user
async def get_current_active_user(
current_user: Annotated[User, Security(get_current_user, scopes=["me"])],
):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username, "scope": " ".join(form_data.scopes)},
expires_delta=access_token_expires,
)
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/")
async def read_users_me(
current_user: Annotated[User, Depends(get_current_active_user)],
) -> User:
return current_user
@app.get("/users/me/items/")
async def read_own_items(
current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])],View on GitHub (pinned to 3e8d1526d8)