tiangolo/fastapi · error · HTTPException
Incorrect username or password
Error message
Incorrect username or password
What it means
In the scopes tutorial, `/token` raises HTTP 400 'Incorrect username or password' when `authenticate_user` returns falsy. The handler uses the same timing-attack mitigation (DUMMY_HASH) as tutorial004, but here the failure status is 400 and scopes are embedded in the resulting JWT's `scope` claim.
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 42a41db11f)
Solutions
- POST credentials as form-encoded; include `scope` only if needed.
- Hash stored passwords with the server's `PasswordHash.recommended()`.
- Install `pwdlib[argon2]`.
- Confirm the user exists and the password verifies.
Example fix
# before curl -X POST http://localhost:8000/token -d 'username=johndoe&password=wrong&scope=me items' # after curl -X POST http://localhost:8000/token -d 'username=johndoe&password=secret&scope=me items'
Defensive patterns
Strategy: try-catch
Validate before calling
def is_form_login(username: str, password: str) -> bool:
return bool(username) and bool(password)
# POST as application/x-www-form-urlencoded when True Type guard
def is_credentials_error(resp) -> bool:
return getattr(resp, 'status_code', None) in (400, 401) and \
resp.json().get('detail') == 'Incorrect username or password' Try / catch
try:
tok = client.post('/token', data={'username': u, 'password': p, 'scope': 'me items'})
tok.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.json().get('detail') == 'Incorrect username or password':
show_user_friendly_login_error()
raise Prevention
- Hash passwords with the server's PasswordHash.recommended().
- Install pwdlib's argon2 extra for argon2id.
- POST form-encoded and keep the generic message; rate-limit /token.
When it happens
Trigger: `POST /token` (form-encoded, optionally with a `scope` field) with an unknown username or a wrong password; both hit `if not user:` at line 156.
Common situations: Password typo; user not provisioned; argon2id hash from a different hasher; pwdlib missing; requesting scopes the user is not entitled to (still fails auth first); JSON instead of form data.
Related errors
- Incorrect username or password
- Incorrect username or password
- Incorrect username or password
- Incorrect username or password
- Incorrect username or password
AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04).
Data as JSON: /data/errors/8b5d2ffd48e1d414.json.
Report an issue: GitHub.