fix: treat empty bearer token as missing credentials in OAuth2 helpers by subhashdasyam · Pull Request #15220 · fastapi/fastapi

Summary

OAuth2PasswordBearer and OAuth2AuthorizationCodeBearer accept Authorization: Bearer (empty token) and return "" instead of triggering the auto_error path.

Fixes the issue raised in #15192.

Root Cause

get_authorization_scheme_param("Bearer ") returns ("Bearer", ""). Both __call__ methods only checked that the scheme was "bearer" — never that the credential string was non-empty.

Fix

Add not param to the guard condition in both OAuth2PasswordBearer.__call__ and OAuth2AuthorizationCodeBearer.__call__:

# before
if not authorization or scheme.lower() != "bearer":

# after
if not authorization or scheme.lower() != "bearer" or not param:

Spec Reference

RFC 6750 Section 2.1 defines the grammar as credentials = "Bearer" 1*SP b64token where b64token = 1*(...) — at least one character required. An empty credential is syntactically malformed and should be treated the same as missing credentials.

Behavior

Request auto_error=True auto_error=False
No Authorization header 401 None
Authorization: Bearer (before) 200, token="" ""
Authorization: Bearer (after) 401 None
Authorization: Bearer validtoken 200 "validtoken"

Tests

  • test_empty_bearer_token in test_security_oauth2_password_bearer_optional.py (auto_error=FalseNone)
  • test_empty_bearer_token in test_security_oauth2_authorization_code_bearer.py (auto_error=True → 401)