tiangolo/fastapi · error · HTTPException

Not authenticated

Error message

Not authenticated

What it means

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.

Source

Thrown at docs_src/security/tutorial003_py310.py:59


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: 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: 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: OAuth2PasswordRequestForm = Depends()):
    user_dict = fake_users_db.get(form_data.username)
    if not user_dict:
        raise HTTPException(status_code=400, detail="Incorrect username or password")

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Obtain a token via POST /token, then call protected routes with `Authorization: Bearer <token>`.
  2. Use a known username as the token for this toy example (`Bearer johndoe`).
  3. Send the complete, untruncated token with the `Bearer ` scheme.

Example fix

# before
curl -H 'Authorization: Bearer stale' 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()
    else:
        raise

Prevention

When it happens

Trigger: `GET /users/me` with `Authorization: Bearer <unknown-username>`. A missing header is intercepted upstream by `OAuth2PasswordBearer` which raises the same 401.

Common situations: 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.

Related errors


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