diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index 33e85d72b..259caae11 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -41,6 +41,8 @@ def __init__( preflight_headers = {} if "*" in allow_origins: preflight_headers["Access-Control-Allow-Origin"] = "*" + if allow_credentials: + preflight_headers["Vary"] = "Origin" else: preflight_headers["Vary"] = "Origin" preflight_headers.update( diff --git a/tests/middleware/test_cors.py b/tests/middleware/test_cors.py index 7dfc2ab6a..ea8e27bdb 100644 --- a/tests/middleware/test_cors.py +++ b/tests/middleware/test_cors.py @@ -34,6 +34,7 @@ def homepage(request): assert response.headers["access-control-allow-origin"] == "https://example.org" assert response.headers["access-control-allow-headers"] == "X-Example" assert response.headers["access-control-allow-credentials"] == "true" + assert response.headers["vary"] == "Origin" # Test standard response headers = {"Origin": "https://example.org"} @@ -89,6 +90,7 @@ def homepage(request): assert response.headers["access-control-allow-origin"] == "*" assert response.headers["access-control-allow-headers"] == "X-Example" assert "access-control-allow-credentials" not in response.headers + assert "vary" not in response.headers # Test standard response headers = {"Origin": "https://example.org"} @@ -206,6 +208,7 @@ def homepage(request): assert response.status_code == 200 assert response.headers["access-control-allow-origin"] == "https://example.org" assert response.headers["access-control-allow-credentials"] == "true" + assert response.headers["vary"] == "Origin" def test_cors_allow_origin_regex():