Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add handling of Authorization header in CORS requests #2506

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions starlette/middleware/cors.py
Expand Up @@ -69,6 +69,7 @@ def __init__(
self.allow_origin_regex = compiled_allow_origin_regex
self.simple_headers = simple_headers
self.preflight_headers = preflight_headers
self.allow_credentials = allow_credentials

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http": # pragma: no cover
Expand Down Expand Up @@ -157,11 +158,13 @@ async def send(
headers.update(self.simple_headers)
origin = request_headers["Origin"]
has_cookie = "cookie" in request_headers
has_authorization = "Authorization" in request_headers

# If request includes any cookie headers, then we must respond
# with the specific origin instead of '*'.
if self.allow_all_origins and has_cookie:
self.allow_explicit_origin(headers, origin)
if self.allow_all_origins:
if self.allow_credentials and has_authorization or has_cookie:
self.allow_explicit_origin(headers, origin)

# If we only allow specific origins, then we have to mirror back
# the Origin header in the response.
Expand Down
9 changes: 9 additions & 0 deletions tests/middleware/test_cors.py
Expand Up @@ -66,6 +66,15 @@ def homepage(request: Request) -> PlainTextResponse:
assert response.headers["access-control-expose-headers"] == "X-Status"
assert response.headers["access-control-allow-credentials"] == "true"

# Test Authorization order
headers = {"Origin": "https://example.org", "Authorization": "Some_token"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-expose-headers"] == "X-Status"
assert response.headers["access-control-allow-credentials"] == "true"

# Test non-CORS response
response = client.get("/")
assert response.status_code == 200
Expand Down