{"id":"8b5d2ffd48e1d414","repo":"tiangolo/fastapi","slug":"incorrect-username-or-password-8b5d2f","errorCode":null,"errorMessage":"Incorrect username or password","messagePattern":"Incorrect username or password","errorType":"http","errorClass":"HTTPException","httpStatus":400,"severity":"error","filePath":"docs_src/security/tutorial005_an_py310.py","lineNumber":157,"sourceCode":"            )\n    return user\n\n\nasync def get_current_active_user(\n    current_user: Annotated[User, Security(get_current_user, scopes=[\"me\"])],\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(status_code=400, detail=\"Incorrect username or password\")\n    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n    access_token = create_access_token(\n        data={\"sub\": user.username, \"scope\": \" \".join(form_data.scopes)},\n        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\n@app.get(\"/users/me/items/\")\nasync def read_own_items(\n    current_user: Annotated[User, Security(get_current_active_user, scopes=[\"items\"])],","sourceCodeStart":139,"sourceCodeEnd":175,"githubUrl":"https://github.com/tiangolo/fastapi/blob/42a41db11f6882807ac3c057b942178d53b97438/docs_src/security/tutorial005_an_py310.py#L139-L175","documentation":"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.","triggerScenarios":"`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.","commonSituations":"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.","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."],"exampleFix":"# before\ncurl -X POST http://localhost:8000/token -d 'username=johndoe&password=wrong&scope=me items'\n# after\ncurl -X POST http://localhost:8000/token -d 'username=johndoe&password=secret&scope=me items'","handlingStrategy":"try-catch","validationCode":"def is_form_login(username: str, password: str) -> bool:\n    return bool(username) and bool(password)\n# POST as application/x-www-form-urlencoded when True","typeGuard":"def is_credentials_error(resp) -> bool:\n    return getattr(resp, 'status_code', None) in (400, 401) and \\\n           resp.json().get('detail') == 'Incorrect username or password'","tryCatchPattern":"try:\n    tok = client.post('/token', data={'username': u, 'password': p, 'scope': 'me items'})\n    tok.raise_for_status()\nexcept httpx.HTTPStatusError as e:\n    if e.response.json().get('detail') == 'Incorrect username or password':\n        show_user_friendly_login_error()\n    raise","preventionTips":["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."],"tags":["authentication","oauth2","login","jwt","scopes","security","fastapi"],"analyzedSha":"42a41db11f6882807ac3c057b942178d53b97438","analyzedAt":"2026-08-04T19:23:32.007Z","schemaVersion":2}