Skip to content

Commit

Permalink
Ensure allow credentials header is not emitted for disallowed origins (
Browse files Browse the repository at this point in the history
…#888)

Co-authored-by: Adam Johnson <[email protected]>
  • Loading branch information
romanek-adam and adamchainz authored Oct 11, 2023
1 parent 9d42ce9 commit b6a7fd7
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
Changelog
=========

* Avoid adding the ``access-control-allow-credentials`` header to unallowed responses.

Thanks to Adam Romanek in `PR #888 <https://github.com/adamchainz/django-cors-headers/pull/888>`__.

* Support Django 5.0.

4.2.0 (2023-07-10)
Expand Down
6 changes: 3 additions & 3 deletions src/corsheaders/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,6 @@ def add_response_headers(
except ValueError:
return response

if conf.CORS_ALLOW_CREDENTIALS:
response[ACCESS_CONTROL_ALLOW_CREDENTIALS] = "true"

if (
not conf.CORS_ALLOW_ALL_ORIGINS
and not self.origin_found_in_white_lists(origin, url)
Expand All @@ -120,6 +117,9 @@ def add_response_headers(
else:
response[ACCESS_CONTROL_ALLOW_ORIGIN] = origin

if conf.CORS_ALLOW_CREDENTIALS:
response[ACCESS_CONTROL_ALLOW_CREDENTIALS] = "true"

if len(conf.CORS_EXPOSE_HEADERS):
response[ACCESS_CONTROL_EXPOSE_HEADERS] = ", ".join(
conf.CORS_EXPOSE_HEADERS
Expand Down
15 changes: 12 additions & 3 deletions tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,22 @@ def test_get_dont_expose_headers(self):
resp = self.client.get("/", HTTP_ORIGIN="https://example.com")
assert ACCESS_CONTROL_EXPOSE_HEADERS not in resp

@override_settings(CORS_ALLOW_CREDENTIALS=True, CORS_ALLOW_ALL_ORIGINS=True)
@override_settings(
CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_ALLOW_CREDENTIALS=True
)
def test_get_allow_credentials(self):
resp = self.client.get("/", HTTP_ORIGIN="https://example.com")
assert resp[ACCESS_CONTROL_ALLOW_CREDENTIALS] == "true"

@override_settings(CORS_ALLOW_ALL_ORIGINS=True)
def test_get_dont_allow_credentials(self):
@override_settings(
CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_ALLOW_CREDENTIALS=True
)
def test_get_allow_credentials_bad_origin(self):
resp = self.client.get("/", HTTP_ORIGIN="https://example.org")
assert ACCESS_CONTROL_ALLOW_CREDENTIALS not in resp

@override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
def test_get_allow_credentials_disabled(self):
resp = self.client.get("/", HTTP_ORIGIN="https://example.com")
assert ACCESS_CONTROL_ALLOW_CREDENTIALS not in resp

Expand Down

0 comments on commit b6a7fd7

Please sign in to comment.