{"id":"8d9d29279d5aba54","repo":"tiangolo/fastapi","slug":"not-authenticated-8d9d29","errorCode":null,"errorMessage":"Not authenticated","messagePattern":"Not authenticated","errorType":"http","errorClass":"HTTPException","httpStatus":401,"severity":"error","filePath":"docs_src/security/tutorial003_py310.py","lineNumber":59,"sourceCode":"\n\ndef get_user(db, username: str):\n    if username in db:\n        user_dict = db[username]\n        return UserInDB(**user_dict)\n\n\ndef fake_decode_token(token):\n    # This doesn't provide any security at all\n    # Check the next version\n    user = get_user(fake_users_db, token)\n    return user\n\n\nasync def get_current_user(token: str = Depends(oauth2_scheme)):\n    user = fake_decode_token(token)\n    if not user:\n        raise HTTPException(\n            status_code=status.HTTP_401_UNAUTHORIZED,\n            detail=\"Not authenticated\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n    return user\n\n\nasync def get_current_active_user(current_user: User = Depends(get_current_user)):\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(form_data: OAuth2PasswordRequestForm = Depends()):\n    user_dict = fake_users_db.get(form_data.username)\n    if not user_dict:\n        raise HTTPException(status_code=400, detail=\"Incorrect username or password\")","sourceCodeStart":41,"sourceCodeEnd":77,"githubUrl":"https://github.com/tiangolo/fastapi/blob/42a41db11f6882807ac3c057b942178d53b97438/docs_src/security/tutorial003_py310.py#L41-L77","documentation":"Identical behavior to the Annotated variant (error 42), in the default-parameter style: `get_current_user(token: str = Depends(oauth2_scheme))` raises HTTP 401 'Not authenticated' when `fake_decode_token(token)` returns no user. The sample 'token' is the raw username, so any token that is not a key in `fake_users_db` fails.","triggerScenarios":"`GET /users/me` with `Authorization: Bearer <unknown-username>`. A missing header is intercepted upstream by `OAuth2PasswordBearer` which raises the same 401.","commonSituations":"Stale/expired token; token from another environment; user record removed; the only runtime difference from error 42 is the dependency declaration style - behavior is the same.","solutions":["Obtain a token via POST /token, then call protected routes with `Authorization: Bearer <token>`.","Use a known username as the token for this toy example (`Bearer johndoe`).","Send the complete, untruncated token with the `Bearer ` scheme."],"exampleFix":"# before\ncurl -H 'Authorization: Bearer stale' http://localhost:8000/users/me\n# after\nTOKEN=$(curl -s -X POST http://localhost:8000/token -d 'username=johndoe&password=secret' | jq -r .access_token)\ncurl -H \"Authorization: Bearer $TOKEN\" http://localhost:8000/users/me","handlingStrategy":"try-catch","validationCode":"import re\ndef looks_like_bearer(header: str | None) -> bool:\n    return bool(header) and re.fullmatch(r'Bearer \\S+', header, re.I) is not None","typeGuard":"def is_not_authenticated(resp) -> bool:\n    return getattr(resp, 'status_code', None) == 401","tryCatchPattern":"try:\n    me = client.get('/users/me', headers=auth_header(token))\n    me.raise_for_status()\nexcept httpx.HTTPStatusError as e:\n    if e.response.status_code == 401:\n        token = refresh_login()\n    else:\n        raise","preventionTips":["Fetch the token from /token before calling protected endpoints.","Handle 401 in one interceptor: refresh once, then retry.","Never silently loop on 401 - it usually means re-auth is required."],"tags":["authentication","oauth2","bearer","security","fastapi"],"analyzedSha":"42a41db11f6882807ac3c057b942178d53b97438","analyzedAt":"2026-08-04T19:23:32.007Z","schemaVersion":2}