tiangolo/fastapi · error · HTTPException

Incorrect username or password

Error message

Incorrect username or password

What it means

Default-parameter twin of error 56: `/token` raises HTTP 400 'Incorrect username or password' when `authenticate_user` returns falsy (line 155). Uses DUMMY_HASH timing mitigation; scopes are placed in the JWT's `scope` claim on success.

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 42a41db11f)

Solutions

  1. POST credentials form-encoded.
  2. Hash stored passwords with the server's `PasswordHash.recommended()`.
  3. Install `pwdlib[argon2]`.
  4. Verify the user exists and the password matches.

Example fix

# before
curl -X POST http://localhost:8000/token -d 'username=johndoe&password=wrong'
# 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

When it happens

Trigger: `POST /token` form-encoded (with optional `scope`) using an unknown username or wrong password.

Common situations: Password typo; user not provisioned; argon2id hash from a different hasher; pwdlib missing; JSON instead of form data.

Related errors


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