Browse Source

Fix HTTP Basic realm handling (RFC 7617)

pull/14697/head
AnshMNSoni 6 months ago
parent
commit
e8c08fc843
  1. 13
      fastapi/security/http.py
  2. 18
      tests/test_security_http_base.py

13
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

18
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"'
Loading…
Cancel
Save