# fastapi.exceptions.HTTPException: 401 Unauthorized: Token expired

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

## Root Cause

OAuth2 令牌已过期，需要刷新

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.9 | active | — | — |
| 3.10 | active | — | — |

## Workarounds

1. **实现令牌刷新机制** (90% success)
   ```
   from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token', auto_error=False)
@app.post('/refresh')
def refresh(token: str = Depends(oauth2_scheme)):
    new_token = create_access_token(...)
    return {'access_token': new_token}
   ```
2. **在客户端捕获 401 并刷新令牌** (85% success)
   ```
   response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
if response.status_code == 401:
    token = refresh_token()
    response = requests.get(url, headers={'Authorization': f'Bearer {token}'})
   ```

## Dead Ends

- **忽略过期并继续使用旧令牌** — 服务器会拒绝请求 (95% fail)
- **延长令牌有效期而不刷新** — 安全风险增加 (70% fail)
