Signing in
The tower-sessions layer keeps a session for each browser, which a cookie points to. An action signs the visitor in by writing the member's name into the session, and signs them out by emptying it.
A session layer
A session is a record on the server that the browser points to with a cookie holding its id. tower-sessions keeps that record, generates the id, and writes the Set-Cookie header, so a handler only reads and writes values in the session. Add it to Cargo.toml:
[dependencies]
tower-sessions = { version = "0.14", default-features = false, features = ["axum-core", "memory-store"] }The sample uses 0.14 although 0.15 is out, because tower-sessions-sqlx-store 0.15, tower-sessions-redis-store 0.16, and axum-login 0.18 depend on tower-sessions-core 0.14, and a store built on it does not implement the SessionStore trait of a 0.15 layer. The repository's auth example uses the same sign-in and sign-out behind a sign-in form.
Signing in and out
The sign-in is an action whose handler takes the session as its extractor, sign_in(state, session: Session, credentials: Credentials), the form Fn(St, E, A) of Handler. The form on the sign-in page sends the Credentials signal as the action's arguments:
use tower_sessions::cookie::SameSite;
use tower_sessions::{MemoryStore, Session, SessionManagerLayer};
/// The key under which a session holds the signed-in member's name.
const MEMBER: &str = "member";
#[derive(Signals, Serialize, Deserialize)]
struct Credentials {
name: String,
password: String,
}
#[derive(Signals, Serialize, Deserialize)]
struct Login {
credentials: Credentials,
problem: String,
}
#[derive(Debug)]
struct StoreFailed(tower_sessions::session::Error);
impl IntoResponse for StoreFailed {
fn into_response(self) -> Response {
eprintln!("session store: {}", self.0);
(StatusCode::INTERNAL_SERVER_ERROR, "Try again.").into_response()
}
}
async fn login(_: AppState, (): ()) -> Page<Login> {
let credentials = Login::credentials();
let signals = Login {
credentials: Credentials { name: String::new(), password: String::new() },
problem: String::new(),
};
Page::new("Sign in", signals).child(
form()
.on_submit(SIGN_IN.call_with(credentials).error(Login::problem()))
.child(input().bind(credentials.at(Credentials::name())))
.child(
input()
.attr(attr::TYPE, "password")
.bind(credentials.at(Credentials::password())),
)
.child(button().text("Sign in"))
.child(p().bind_text(Login::problem())),
)
}
async fn sign_in(
_: AppState,
session: Session,
credentials: Credentials,
) -> Result<Patches<Login>, StoreFailed> {
if !checked(&credentials.name, &credentials.password) {
let wrong = "The name or the password is wrong.".to_owned();
return Ok(Login::problem().patch(wrong).into());
}
session.cycle_id().await.map_err(StoreFailed)?;
session.insert(MEMBER, credentials.name).await.map_err(StoreFailed)?;
Ok(Patches::new().navigate(HOME.url(())))
}
async fn sign_out(_: AppState, session: Session, (): ()) -> Result<Patches<Home>, StoreFailed> {
session.flush().await.map_err(StoreFailed)?;
Ok(Patches::new().navigate(LOGIN.url(())))
}
hypersig::routes! {
fn pages(Router<AppState>);
const HOME: Route = "/" => home;
const LOGIN: Route = "/login" => login;
action SIGN_IN: Action<Login, Credentials> = post "/sign-in" => sign_in;
action SIGN_OUT: Action<Home> = post "/sign-out" => sign_out;
}
let sessions = SessionManagerLayer::new(MemoryStore::default())
.with_name("session")
.with_same_site(SameSite::Lax);
let _app: Router = pages(Router::new())
.hypersig_runtime()
.with_state(AppState)
.layer(sessions);SessionManagerLayer wraps the router, so it runs around every page, action, and stream. It reads the id from the cookie and hands each handler a Session, which loads the record from the store the first time a handler reads it. After the handler returns its response, the layer saves a session the handler changed and sets the cookie on that response, or removes the cookie of a session the handler emptied. The layer saves nothing when the status is a 5xx, and a change a stream makes to the session after its response has started is not saved.
A new id at sign-in
The sign-in calls cycle_id before it puts the name in the session. Without it, someone who placed the id of their own session in the visitor's browser would hold the same id after the visitor signs in, and would be signed in as the visitor. With it, the session that holds the member has a new id, and the store no longer has the old one. The sign-out calls flush, which deletes the record from the store and empties the session, and the layer then removes the cookie.
The page the browser goes to next
Patches::navigate is fn navigate(self, url: Url) -> Self, and loads the page at url once the patches before it are applied. A Url comes from a route, as HOME.url(()), so a path written as a string fails to compile with E0308:
// `navigate` takes a `Url`, which only a route's `url` builds.
let _signed_in: Patches<Login> = Patches::new().navigate("/");A name and password that do not match answer with a patch of problem, which the page shows under the form. The session stays unchanged, so the layer sets no cookie. Links and redirects covers sending the browser to another page in general.
What goes over the network
The sign-in's answer carries the cookie in a Set-Cookie header, in the same response as the patch that sends the browser home. The browser stores the cookie before it moves, so the request for the home page already carries it:
HTTP/1.1 200 OK
set-cookie: session=NopwG88FsWT6bJHopbZRSw; HttpOnly; SameSite=Lax; Secure; Path=/The sign-out's answer, beside the patch that sends the browser to the sign-in page, replaces the cookie with an empty one that has already expired, and the browser deletes it:
HTTP/1.1 200 OK
set-cookie: session=; Path=/; Max-Age=0; Expires=Tue, 28 Oct 2025 16:14:13 GMTChecking the password
checked in the sample stands for the password check. The auth example keeps each password as an Argon2 hash that password-auth writes, and checks a sign-in with verify_password on tokio::task::spawn_blocking, because Argon2 spends its time on the CPU on purpose, about 10 ms in a release build. A name no member has is checked against a hash as well, so the answer takes as long as a member's and does not tell which names exist.
Next
- Pages for signed-in members reads the member from the session and turns everyone else away.
- The session cookie covers the cookie's attributes and how long it lasts.
- Where sessions are stored replaces
MemoryStorefor a server with more than one instance. - Testing handlers calls
sign_infrom a test with aSessionthe test builds.