diff --git a/fastapi/security/http.py b/fastapi/security/http.py index f41d8d944..362390b7a 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -112,10 +112,13 @@ class HTTPBearer(HTTPBase): else: return None if scheme.lower() != "bearer": - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail="Invalid authentication credentials", - ) + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) diff --git a/tests/test_security_http_bearer_optional.py b/tests/test_security_http_bearer_optional.py index 5a690c521..d34433ec0 100644 --- a/tests/test_security_http_bearer_optional.py +++ b/tests/test_security_http_bearer_optional.py @@ -64,5 +64,5 @@ def test_security_http_bearer_no_credentials(): def test_security_http_bearer_incorrect_scheme_credentials(): response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) - assert response.status_code == 403 - assert response.json() == {"detail": "Invalid authentication credentials"} + assert response.status_code == 200 + assert response.json() == {"msg": "Create an account first"}