actix / actix-extras

A collection of additional crates supporting the actix and actix-web frameworks.
https://actix.rs
Apache License 2.0
787 stars 206 forks source link

Session: add cookie max age #323

Closed LinuxHeki closed 1 month ago

LinuxHeki commented 1 year ago

Expected Behavior

There should be a way to set max age for cookies.

Current Behavior

Currently you can't change cookie max age.

Possible Solution

We could add cookie_max_age() function that accepts u32/usize/Duration as argument to SessionMiddlewareBuilder.

Context

This could allow to preserve session after browser is closed, and for example users won't have to log in every time they open a browser.

junbl commented 3 months ago

Believe you can do this with SessionLifecycle

https://docs.rs/actix-session/latest/actix_session/config/struct.SessionMiddlewareBuilder.html#method.session_lifecycle https://docs.rs/actix-session/latest/actix_session/config/struct.PersistentSession.html#method.session_ttl

From those docs:

use actix_web::cookie::{Key, time::Duration};
use actix_session::{SessionMiddleware, config::PersistentSession};
use actix_session::storage::CookieSessionStore;

const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;

// creates a session middleware with a time-to-live (expiry) of 1 week
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
    .session_lifecycle(
        PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK))
    )
    .build();
jwiesler commented 1 month ago

This saved me. I always had sporadic logouts in some mobile browsers until I noticed the cookie max age.