tiangolo/fastapi · error · HTTPException

Incorrect username or password

Error message

Incorrect username or password

What it means

In the JWT tutorial, `/token` raises HTTP 401 'Incorrect username or password' (with `WWW-Authenticate: Bearer`) when `authenticate_user(...)` returns falsy. Unlike tutorial003's 400, this version uses 401 and runs a `DUMMY_HASH` verify when the user is unknown to blunt timing-based user enumeration.

Source

Thrown at docs_src/security/tutorial004_an_py310.py:127

        raise credentials_exception
    return user


async def get_current_active_user(
    current_user: Annotated[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: Annotated[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: Annotated[User, Depends(get_current_active_user)],
) -> User:
    return current_user

View on GitHub (pinned to 42a41db11f)

Solutions

  1. POST credentials as `application/x-www-form-urlencoded`.
  2. Generate the stored hash with the same `PasswordHash.recommended()` the app uses: `password_hash.hash('secret')`.
  3. Ensure `pwdlib` is installed (`pip install pwdlib[argon2]`).
  4. Confirm the username exists and the hash verifies before reporting success.

Example fix

# before
# stored hash produced by a different hasher => always 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 with Content-Type: 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

When it happens

Trigger: `POST /token` with an unknown username OR a known username with the wrong password - both fall through the single `if not user:` branch at line 126. The sample uses argon2id hashes via pwdlib.

Common situations: Password typo; user not provisioned; argon2id hash in the DB malformed or generated with a different hasher; `pwdlib` not installed or `PasswordHash.recommended()` changed scheme across versions; JSON sent instead of form data.

Related errors


AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04). Data as JSON: /data/errors/232b87a1b4780a32.json. Report an issue: GitHub.