diff --git a/fastapi/security/http.py b/fastapi/security/http.py index b4c3bc6d8..25cb4e376 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -152,14 +152,7 @@ class HTTPBasic(HTTPBase): """ ), ] = None, - realm: Annotated[ - Optional[str], - Doc( - """ - HTTP Basic authentication realm. - """ - ), - ] = None, + realm: Annotated[str, Doc("HTTP Basic authentication realm.")] = "fastapi", description: Annotated[ Optional[str], Doc( @@ -197,9 +190,7 @@ class HTTPBasic(HTTPBase): self.auto_error = auto_error def make_authenticate_headers(self) -> dict[str, str]: - if self.realm: - return {"WWW-Authenticate": f'Basic realm="{self.realm}"'} - return {"WWW-Authenticate": "Basic"} + return {"WWW-Authenticate": f'Basic realm="{self.realm}"'} async def __call__( # type: ignore self, request: Request diff --git a/tests/test_security_http_base.py b/tests/test_security_http_base.py index 8cf259a75..debd97bcc 100644 --- a/tests/test_security_http_base.py +++ b/tests/test_security_http_base.py @@ -1,6 +1,7 @@ -from fastapi import FastAPI, Security +from fastapi import FastAPI, Security, Depends from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBase from fastapi.testclient import TestClient +from fastapi.security import HTTPBasic app = FastAPI() @@ -53,3 +54,18 @@ def test_openapi_schema(): "securitySchemes": {"HTTPBase": {"type": "http", "scheme": "Other"}} }, } + +def test_http_basic_includes_realm(): + app = FastAPI() + security = HTTPBasic(realm="MyRealm") + + @app.get("/") + def read_root(credentials=Depends(security)): + return {"ok": True} + + client = TestClient(app) + response = client.get("/") + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == 'Basic realm="MyRealm"' + \ No newline at end of file