tiangolo/fastapi · error · HTTPException
Incorrect username or password
Error message
Incorrect username or password
What it means
Legacy-DI variant of error 53. The /token handler raises HTTP 400 'Incorrect username or password' when authenticate_user is falsy (unknown username or failed password verify, the latter timed against DUMMY_HASH for unknown users). Note the 400-vs-401 inconsistency with tutorial004.
Solutions
- POST username + password matching a seeded user.
- Regenerate stored hashes if the hasher changed.
- Use 401 with WWW-Authenticate for RFC 6749 consistency.
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 form-encoded credentials and scopes.
- Regenerate stored hashes when the hasher changes.
- Do not auto-retry with the same credentials.
When it happens
Trigger: POST /token form-encoded with username not in {johndoe, alice} or a wrong password.
Common situations: Wrong password; missing username; regenerated hashes; JSON body instead of form data.
Related errors
AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11).
Data as JSON: /api/errors/2ac4b64bf11d5467.
Report an issue: GitHub.
Appendix: source
Thrown at docs_src/security/tutorial005_py310.py:156
)
return user
async def get_current_active_user(
current_user: 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: 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: User = Depends(get_current_active_user)) -> User:
return current_user
@app.get("/users/me/items/")
async def read_own_items(
current_user: User = Security(get_current_active_user, scopes=["items"]),
):
return [{"item_id": "Foo", "owner": current_user.username}]View on GitHub (pinned to 3e8d1526d8)