# FastAPI HTTP异常：401未授权：未验证

- **ID:** `python/fastapi-oauth2-token-error`
- **领域:** python
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

请求不包含有效的OAuth2令牌或令牌缺失。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

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

## 无效尝试

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