* Allow Session scoped cookies.
* Update docs/middleware.md
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
* Improve typing.
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
* `secret_key` - Should be a random string.
* `session_cookie` - Defaults to "session".
-* `max_age` - Session expiry time in seconds. Defaults to 2 weeks.
+* `max_age` - Session expiry time in seconds. Defaults to 2 weeks. If set to `None` then the cookie will last as long as the browser session.
* `same_site` - SameSite flag prevents the browser from sending session cookie along with cross-site requests. Defaults to `'lax'`.
* `https_only` - Indicate that Secure flag should be set (can be used with HTTPS only). Defaults to `False`.
app: ASGIApp,
secret_key: typing.Union[str, Secret],
session_cookie: str = "session",
- max_age: int = 14 * 24 * 60 * 60, # 14 days, in seconds
+ max_age: typing.Optional[int] = 14 * 24 * 60 * 60, # 14 days, in seconds
same_site: str = "lax",
https_only: bool = False,
) -> None:
data = b64encode(json.dumps(scope["session"]).encode("utf-8"))
data = self.signer.sign(data)
headers = MutableHeaders(scope=message)
- header_value = "%s=%s; path=%s; Max-Age=%d; %s" % (
- self.session_cookie,
- data.decode("utf-8"),
- path,
- self.max_age,
- self.security_flags,
+ header_value = "{session_cookie}={data}; path={path}; {max_age}{security_flags}".format( # noqa E501
+ session_cookie=self.session_cookie,
+ data=data.decode("utf-8"),
+ path=path,
+ max_age=f"Max-Age={self.max_age}; " if self.max_age else "",
+ security_flags=self.security_flags,
)
headers.append("Set-Cookie", header_value)
elif not initial_session_was_empty:
# we expect it to not raise an exception if we provide a bogus session cookie
response = client.get("/view_session", cookies={"session": "invalid"})
assert response.json() == {"session": {}}
+
+
+def test_session_cookie(test_client_factory):
+ app = create_app()
+ app.add_middleware(SessionMiddleware, secret_key="example", max_age=None)
+ client = test_client_factory(app)
+
+ response = client.post("/update_session", json={"some": "data"})
+ assert response.json() == {"session": {"some": "data"}}
+
+ # check cookie max-age
+ set_cookie = response.headers["set-cookie"]
+ assert "Max-Age" not in set_cookie
+
+ client.cookies.clear_session_cookies()
+ response = client.get("/view_session")
+ assert response.json() == {"session": {}}