python
data_error
ai_generated
true
KeyError: 'Authorization'
ID: python/starlette-request-headers-missing
80%Fix Rate
88%Confidence
0Evidence
2024-04-25First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
在 Starlette 中直接访问 request.headers['Authorization'],但请求未包含该头部。
generic中文
在 Starlette 中直接访问 request.headers['Authorization'],但请求未包含该头部。
Workarounds
-
95% success
auth = request.headers.get('Authorization') if auth is None: return JSONResponse({'error': 'missing'}, status_code=401) -
90% success
auth = request.headers.get('Authorization', '')
Dead Ends
Common approaches that don't work:
-
50% fail
头部名称不区分大小写,但拼写错误会导致返回 None,后续逻辑出错。
-
60% fail
未处理缺失头部的情况,可能导致未授权访问。