日本語

The session cookie

The session's cookie is HttpOnly, Secure, and SameSite=Strict unless the layer says otherwise, and lasts until the browser closes unless the layer is given an expiry.

SessionManagerLayer gives the cookie these attributes unless the builder says otherwise. The sample on Signing in changes two of them:

AttributeDefaultThe sampleBuilder method
Nameidsessionwith_name
HttpOnlyOnOnwith_http_only
SecureOnOnwith_secure
SameSiteStrictLaxwith_same_site
Path//with_path
Max-AgeNoneNonewith_expiry

With Strict, the browser leaves the cookie off a visit that follows a link from another site, such as a link in an email, and that visit lands on the sign-in page. The sample sets Lax, which sends the cookie on such a visit. An action needs no Strict, because it refuses a request another site sends, as Security lists.

HttpOnly keeps the cookie out of document.cookie, so a script on the page cannot read the id. Secure keeps the cookie to HTTPS. Chrome also stores it from http://127.0.0.1, where the repository's browser tests run. WebKit, which Safari uses, stores it from neither http://127.0.0.1 nor http://localhost, and lands back on the sign-in page after signing in, so a sign-in in Safari is tried over HTTPS.

Without an expiry the cookie has no Max-Age, so the browser drops it when it closes. With with_expiry(Expiry::OnInactivity(duration)), the cookie gets a Max-Age of duration each time the layer saves the session, and the visitor stays signed in across a restart of the browser:

use tower_sessions::cookie::SameSite;
use tower_sessions::cookie::time::Duration;
use tower_sessions::{Expiry, MemoryStore, SessionManagerLayer};

let sessions = SessionManagerLayer::new(MemoryStore::default())
    .with_name("session")
    .with_same_site(SameSite::Lax)
    .with_expiry(Expiry::OnInactivity(Duration::days(7)));
set-cookie: session=NopwG88FsWT6bJHopbZRSw; HttpOnly; SameSite=Lax; Secure; Path=/; Max-Age=604800

The layer saves only a session a handler changed, so a visitor who only reads pages is signed out duration after the last change. with_always_save(true) saves the session on every response, so the time counts from the last request.

Next