Skip to content

Commit

Permalink
Make session cookie use ASGI root path (#1147)
Browse files Browse the repository at this point in the history
* Make session cookie use ASGI root path

* Check if ASGI root_path exists before using it

Co-authored-by: Tom Christie <tom@tomchristie.com>

* Remove comment

* Add test

Co-authored-by: Mahmoud Hanafy <mahmoud.hanafy@retresco.de>
Co-authored-by: Tom Christie <tom@tomchristie.com>
  • Loading branch information
3 people committed Mar 12, 2021
1 parent 23e1578 commit 5ee04ef
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
6 changes: 4 additions & 2 deletions starlette/middleware/sessions.py
Expand Up @@ -49,14 +49,16 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:

async def send_wrapper(message: Message) -> None:
if message["type"] == "http.response.start":
path = scope.get("root_path", "") or "/"
if scope["session"]:
# We have session data to persist.
data = b64encode(json.dumps(scope["session"]).encode("utf-8"))
data = self.signer.sign(data)
headers = MutableHeaders(scope=message)
header_value = "%s=%s; path=/; Max-Age=%d; %s" % (
header_value = "%s=%s; path=%s; Max-Age=%d; %s" % (
self.session_cookie,
data.decode("utf-8"),
path,
self.max_age,
self.security_flags,
)
Expand All @@ -66,7 +68,7 @@ async def send_wrapper(message: Message) -> None:
headers = MutableHeaders(scope=message)
header_value = "{}={}; {}".format(
self.session_cookie,
"null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT;",
f"null; path={path}; expires=Thu, 01 Jan 1970 00:00:00 GMT;",
self.security_flags,
)
headers.append("Set-Cookie", header_value)
Expand Down
12 changes: 12 additions & 0 deletions tests/middleware/test_session.py
Expand Up @@ -101,3 +101,15 @@ def test_secure_session():

response = secure_client.get("/view_session")
assert response.json() == {"session": {}}


def test_session_cookie_subpath():
app = create_app()
second_app = create_app()
second_app.add_middleware(SessionMiddleware, secret_key="example")
app.mount("/second_app", second_app)
client = TestClient(app, base_url="http://testserver/second_app")
response = client.post("second_app/update_session", json={"some": "data"})
cookie = response.headers["set-cookie"]
cookie_path = re.search(r"; path=(\S+);", cookie).groups()[0]
assert cookie_path == "/second_app"

0 comments on commit 5ee04ef

Please sign in to comment.