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

Make session cookie use ASGI root path #1147

Merged
Merged
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
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"