{"record":{"id":"3baadc72a93d71de","repo":"tiangolo/fastapi","slug":"inactive-user-3baadc","errorCode":null,"errorMessage":"Inactive user","messagePattern":"Inactive user","errorType":"http","errorClass":"HTTPException","httpStatus":400,"severity":"error","filePath":"docs_src/security/tutorial004_an_py310.py","lineNumber":117,"sourceCode":"    try:\n        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n        username = payload.get(\"sub\")\n        if username is None:\n            raise credentials_exception\n        token_data = TokenData(username=username)\n    except InvalidTokenError:\n        raise credentials_exception\n    user = get_user(fake_users_db, username=token_data.username)\n    if user is None:\n        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    )","sourceCodeStart":99,"sourceCodeEnd":135,"githubUrl":"https://github.com/tiangolo/fastapi/blob/3e8d1526d83a90aaf7d6eb6dc682bf150f180b25/docs_src/security/tutorial004_an_py310.py#L99-L135","documentation":"Disabled-account gate in the JWT tutorial (tutorial004). After get_current_user validates the JWT signature, decodes the 'sub' claim, and loads the user, get_current_active_user checks current_user.disabled and raises HTTP 400. Reaching this line means the token was fully valid and the user exists — only the disabled flag fails. The tutorial ships only johndoe (disabled=False), so the as-shipped code never reaches this line unless a disabled user is added.","triggerScenarios":"Add a user with disabled=True to fake_users_db, obtain a valid JWT for them via POST /token, then call GET /users/me/ — the token decodes and loads the user, then line 116 raises.","commonSituations":"Suspended/banned accounts in production; a second fixture user left disabled; soft-deleted accounts modelled via the disabled flag.","solutions":["Set disabled=False for the user in fake_users_db and re-login to mint a fresh JWT.","Return 403 Forbidden for disabled-but-authenticated users instead of HTTP 400.","Use a distinct 'suspended' status rather than overloading 'disabled' for soft-deletion."],"exampleFix":"// before\nif current_user.disabled:\n    raise HTTPException(status_code=400, detail=\"Inactive user\")\n\n// after\nif current_user.disabled:\n    raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=\"Inactive user\")","handlingStrategy":"try-catch","validationCode":"# JWT version: decode locally to inspect disabled state before calling\nimport jwt\ndef user_disabled_for_token(token: str, db: dict) -> bool:\n    payload = jwt.decode(token, SECRET_KEY, algorithms=[\"HS256\"])\n    u = db.get(payload.get(\"sub\"))\n    return bool(u and u.get(\"disabled\"))","typeGuard":"from typing import TypeGuard\ndef is_active_user(u: dict) -> TypeGuard[dict]:\n    return not u.get(\"disabled\", False)","tryCatchPattern":"import httpx\ntry:\n    r = httpx.get(\"/users/me/\", headers={\"Authorization\": f\"Bearer {token}\"})\n    r.raise_for_status()\nexcept httpx.HTTPStatusError as e:\n    if e.response.status_code in (400, 403) and \"Inactive\" in e.response.text:\n        prompt_reactivation()","preventionTips":["Short JWT TTLs so disabled state is enforced quickly after suspension.","Maintain a revocation list (jti) for disabled accounts.","Prefer 403 Forbidden over 400 for disabled-but-authenticated users."],"tags":["fastapi","authentication","jwt","authorization","python"],"backgroundTag":null,"analyzedSha":"3e8d1526d83a90aaf7d6eb6dc682bf150f180b25","analyzedAt":"2026-08-11T02:34:52.986Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}