tiangolo/fastapi · error · HTTPException

Not authenticated

Error message

Not authenticated

What it means

Raised by `get_current_user` with HTTP 401 when the bearer token cannot be resolved to a user. In this tutorial `fake_decode_token` looks the token up directly as a username in `fake_users_db`, so any token that is not a known username triggers it. The response sets `WWW-Authenticate: Bearer` so clients/OAuth2 flows know to re-authenticate.

Source

Thrown at docs_src/security/tutorial003_an_py310.py:61


def get_user(db, username: str):
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)


def fake_decode_token(token):
    # This doesn't provide any security at all
    # Check the next version
    user = get_user(fake_users_db, token)
    return user


async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    user = fake_decode_token(token)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Depends(get_current_user)],
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    user_dict = fake_users_db.get(form_data.username)

View on GitHub (pinned to 42a41db11f)

Solutions

  1. POST /token with valid form credentials to obtain a fresh access token, then retry.
  2. For this example the token is the username, so send `Authorization: Bearer johndoe`.
  3. Make sure the client sends the full, untruncated token using the `Bearer ` scheme.

Example fix

# before
curl -H 'Authorization: Bearer expired' http://localhost:8000/users/me
# after
TOKEN=$(curl -s -X POST http://localhost:8000/token -d 'username=johndoe&password=secret' | jq -r .access_token)
curl -H "Authorization: Bearer $TOKEN" http://localhost:8000/users/me
Defensive patterns

Strategy: try-catch

Validate before calling

import re
def looks_like_bearer(header: str | None) -> bool:
    return bool(header) and re.fullmatch(r'Bearer \S+', header, re.I) is not None

Type guard

def is_not_authenticated(resp) -> bool:
    return getattr(resp, 'status_code', None) == 401

Try / catch

try:
    me = client.get('/users/me', headers=auth_header(token))
    me.raise_for_status()
except httpx.HTTPStatusError as e:
    if e.response.status_code == 401:
        token = refresh_login()  # re-login, then retry once
    else:
        raise

Prevention

When it happens

Trigger: `GET /users/me` with `Authorization: Bearer nobody` (unknown username), or a token belonging to a since-removed user record. (A missing/malformed header is caught earlier by `OAuth2PasswordBearer`, which raises the same 401 'Not authenticated'.)

Common situations: Stale token cached after logout; token from a different environment; user record deleted; token truncated during copy-paste; in this toy app the token literally equals the username so any typo fails.

Related errors


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