python data_error ai_generated true

KeyError: 'Authorization'

ID: python/starlette-request-headers-missing

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

在 Starlette 中直接访问 request.headers['Authorization'],但请求未包含该头部。

generic

中文

在 Starlette 中直接访问 request.headers['Authorization'],但请求未包含该头部。

Workarounds

  1. 95% success
    auth = request.headers.get('Authorization')
    if auth is None:
        return JSONResponse({'error': 'missing'}, status_code=401)
  2. 90% success
    auth = request.headers.get('Authorization', '')

Dead Ends

Common approaches that don't work:

  1. 50% fail

    头部名称不区分大小写,但拼写错误会导致返回 None,后续逻辑出错。

  2. 60% fail

    未处理缺失头部的情况,可能导致未授权访问。