tiangolo/fastapi · error · HTTPException
Incorrect username or password
Error message
Incorrect username or password
What it means
Default-parameter twin of error 51: `/token` raises HTTP 401 'Incorrect username or password' (with `WWW-Authenticate: Bearer`) when `authenticate_user` returns falsy. A `DUMMY_HASH` verify runs for unknown users to flatten timing differences. Behavior matches the Annotated version.
Source
Thrown at docs_src/security/tutorial004_py310.py:124
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)):
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=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, 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 = Depends(get_current_active_user)):View on GitHub (pinned to 42a41db11f)
Solutions
- POST credentials form-encoded.
- Produce the stored hash with the same `PasswordHash.recommended()` the app uses.
- Install `pwdlib[argon2]` if using argon2id.
- Verify the username exists and the hash verifies.
Example fix
# before
# hash made by a different hasher => 401
# after
from pwdlib import PasswordHash
ph = PasswordHash.recommended()
db['johndoe']['hashed_password'] = ph.hash('secret') 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) == 401 and \
resp.json().get('detail') == 'Incorrect username or password' Try / catch
try:
tok = client.post('/token', data={'username': u, 'password': p})
tok.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401 and 'Incorrect' in e.response.text:
show_user_friendly_login_error()
raise Prevention
- Hash stored passwords with the server's PasswordHash.recommended().
- Install pwdlib's argon2 extra when using argon2id.
- POST form-encoded; keep the generic message; rate-limit.
When it happens
Trigger: `POST /token` with an unknown username or a known username + wrong password; both hit `if not user:` at line 123.
Common situations: Password typo; user not provisioned; argon2id hash mismatch from a different hasher; pwdlib missing/wrong version; JSON body 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/9f7f33fb9d084c8a.json.
Report an issue: GitHub.