# fastapi.exceptions.HTTPException: 401 Unauthorized: Not authenticated

- **ID:** `python/fastapi-oauth2-token-error`
- **Domain:** python
- **Category:** auth_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

The request does not contain a valid OAuth2 token or the token is missing.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **Include a valid OAuth2 token in the Authorization header** (95% success)
   ```
   Authorization: Bearer <your_token>
   ```
2. **Implement token validation using OAuth2PasswordBearer** (90% success)
   ```
   from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get('/protected')
async def protected(token: str = Depends(oauth2_scheme)):
    return {"token": token}
   ```

## Dead Ends

- **Removing authentication from the endpoint** — Exposes the endpoint without security. (70% fail)
- **Using a hardcoded token without validation** — Insecure; token can be easily guessed. (80% fail)
