{"id":"232b87a1b4780a32","repo":"tiangolo/fastapi","slug":"incorrect-username-or-password-232b87","errorCode":null,"errorMessage":"Incorrect username or password","messagePattern":"Incorrect username or password","errorType":"http","errorClass":"HTTPException","httpStatus":401,"severity":"error","filePath":"docs_src/security/tutorial004_an_py310.py","lineNumber":127,"sourceCode":"        raise credentials_exception\n    return user\n\n\nasync def get_current_active_user(\n    current_user: Annotated[User, Depends(get_current_user)],\n):\n    if current_user.disabled:\n        raise HTTPException(status_code=400, detail=\"Inactive user\")\n    return current_user\n\n\n@app.post(\"/token\")\nasync def login_for_access_token(\n    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],\n) -> Token:\n    user = authenticate_user(fake_users_db, form_data.username, form_data.password)\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_401_UNAUTHORIZED,\n            detail=\"Incorrect username or password\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n    access_token = create_access_token(\n        data={\"sub\": user.username}, expires_delta=access_token_expires\n    )\n    return Token(access_token=access_token, token_type=\"bearer\")\n\n\n@app.get(\"/users/me/\")\nasync def read_users_me(\n    current_user: Annotated[User, Depends(get_current_active_user)],\n) -> User:\n    return current_user\n\n","sourceCodeStart":109,"sourceCodeEnd":145,"githubUrl":"https://github.com/tiangolo/fastapi/blob/42a41db11f6882807ac3c057b942178d53b97438/docs_src/security/tutorial004_an_py310.py#L109-L145","documentation":"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.","triggerScenarios":"`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.","commonSituations":"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.","solutions":["POST credentials as `application/x-www-form-urlencoded`.","Generate the stored hash with the same `PasswordHash.recommended()` the app uses: `password_hash.hash('secret')`.","Ensure `pwdlib` is installed (`pip install pwdlib[argon2]`).","Confirm the username exists and the hash verifies before reporting success."],"exampleFix":"# before\n# stored hash produced by a different hasher => always 401\n# after\nfrom pwdlib import PasswordHash\nph = PasswordHash.recommended()\ndb['johndoe']['hashed_password'] = ph.hash('secret')","handlingStrategy":"try-catch","validationCode":"def is_form_login(username: str, password: str) -> bool:\n    return bool(username) and bool(password)\n# POST with Content-Type: application/x-www-form-urlencoded when True","typeGuard":"def is_credentials_error(resp) -> bool:\n    return getattr(resp, 'status_code', None) == 401 and \\\n           resp.json().get('detail') == 'Incorrect username or password'","tryCatchPattern":"try:\n    tok = client.post('/token', data={'username': u, 'password': p})\n    tok.raise_for_status()\nexcept httpx.HTTPStatusError as e:\n    if e.response.status_code == 401 and 'Incorrect' in e.response.text:\n        show_user_friendly_login_error()\n    raise","preventionTips":["Generate stored hashes with the exact PasswordHash.recommended() the server uses.","Install the argon2 extra for pwdlib if you rely on argon2id hashes.","POST /token as form-encoded, never JSON.","Rate-limit /token to slow brute force."],"tags":["authentication","oauth2","login","jwt","security","fastapi"],"analyzedSha":"42a41db11f6882807ac3c057b942178d53b97438","analyzedAt":"2026-08-04T19:23:32.007Z","schemaVersion":2}