Session cookie on login

Learn how a login handler stores the user id in the session so the server sets a session cookie, and what that cookie holds

A login handler has two jobs, and only the first one is checking the password. The second job is remembering the answer, so the visitor does not have to prove who they are on every request that follows. This page does that second job: after the password checks out, the handler stores the user id in the session. Storing it is what makes the server send a session cookie back, and that cookie is what keeps the visitor logged in.

Where This Fits

The session layer is already wired onto the router, and it knows how to carry a session from one request to the next. Nothing has written into a session yet, so every session is still empty. This page writes the first value: the user id, stored at the moment the password is proven correct. The value sits in the session from here on, and the pages that follow read it back, end it on logout, and check for it before letting a request through.

Think of the coat check again. Checking the password is showing your invitation at the door. Storing the user id is handing over your coat and taking the ticket. The invitation is checked once and put away. The ticket is what you carry for the rest of the evening.

The Smallest Working Version

The login handler below is complete: it looks the user up by email, checks the submitted password against the stored hash, stores the user id in the session, and returns the user as JSON. Every failure, a missing user, a missing hash, or a wrong password, answers with the same generic 401 and the same body, so nothing about the failure leaks which part was wrong.

The project needs the database and password crates alongside the session crate. The Cargo.toml for this page is:

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
tower-sessions = "0.15"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["postgres", "runtime-tokio"] }
argon2 = "0.6"
thiserror = "2"
time = "0.3"

The users table comes from two migrations. The first creates the table, the second adds the password hash column. A migration is a versioned SQL file that changes the database schema, and SQLx applies the files in version order. The password hash column is nullable, which means it may hold no value: a user with no hash simply cannot log in with a password.

migrations/20261114062321_create_users_table.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
migrations/20261114140000_add_password_hash.sql
ALTER TABLE users ADD COLUMN password_hash TEXT;

The error type is shared by every handler in this project. AppError is an enum, a type with a fixed set of variants, and each variant maps to one status code and one message. The body is always JSON of the shape {"error": "..."}. The Unauthorized variant is the one this page returns, and it maps to status 401 with the message unauthorized. A 401 means the server does not know who is asking.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
    #[error("unauthorized")]
    Unauthorized,
    #[error("forbidden")]
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound => StatusCode::NOT_FOUND,
            AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::Unauthorized => StatusCode::UNAUTHORIZED,
            AppError::Forbidden => StatusCode::FORBIDDEN,
        };
        let body = Json(json!({ "error": self.to_string() }));
        (status, body).into_response()
    }
}

pub type HandlerResult<T> = Result<T, AppError>;

The library file holds the application. app builds the router with the session layer and the two routes, login does the work, and public is a route anyone can read, there so the difference between a guarded route and an open one stays visible.

src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use errors::{AppError, HandlerResult};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
use time::Duration;

#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginInput {
    pub email: String,
    pub password: String,
}

#[derive(Debug, sqlx::FromRow)]
struct LoginRow {
    id: i32,
    password_hash: Option<String>,
}

pub fn app(pool: PgPool) -> Router {
    let session_store = MemoryStore::default();
    let session_layer = SessionManagerLayer::new(session_store)
        .with_secure(false)
        .with_expiry(Expiry::OnInactivity(Duration::days(7)));

    Router::new()
        .route("/login", post(login))
        .route("/public", get(public))
        .layer(session_layer)
        .with_state(pool)
}

async fn public() -> &'static str {
    "Anyone can read this."
}

fn password_matches(password: &str, stored_hash: &str) -> bool {
    let parsed = match PasswordHash::new(stored_hash) {
        Ok(parsed) => parsed,
        Err(_) => return false,
    };
    Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok()
}

async fn login(
    State(pool): State<PgPool>,
    session: Session,
    Json(input): Json<LoginInput>,
) -> HandlerResult<Json<User>> {
    let row = sqlx::query_as::<_, LoginRow>(
        "SELECT id, password_hash FROM users WHERE email = $1",
    )
    .bind(&input.email)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    let user_id = match row {
        Some(row) => match row.password_hash {
            Some(hash) if password_matches(&input.password, &hash) => row.id,
            _ => return Err(AppError::Unauthorized),
        },
        None => return Err(AppError::Unauthorized),
    };

    session
        .insert("user_id", user_id)
        .await
        .map_err(|_| AppError::InternalError)?;
    session
        .cycle_id()
        .await
        .map_err(|_| AppError::InternalError)?;

    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_one(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    Ok(Json(user))
}

The entry point connects to the database, runs the migrations, builds the router, and serves it. DATABASE_URL is the connection string for Postgres, and this project uses the database named ch13_sessions.

src/main.rs
use axum_project::app;
use sqlx::PgPool;

#[tokio::main]
async fn main() {
    let pool = PgPool::connect("postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_sessions")
        .await
        .unwrap();
    sqlx::migrate!("./migrations").run(&pool).await.unwrap();

    let app = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Seed one user first, with a password hash made by the argon2 crate. The hash is a PHC string, a single text value that bundles the algorithm, its parameters, the salt, and the hash itself. It starts with $argon2id$v=19$. Storing the hash, never the password, is what makes the check possible without keeping the password anywhere. For this test the password is test-password-123, a throwaway value for local development only:

INSERT INTO users (name, email, password_hash)
VALUES ('Ada', 'ada@example.com', '$argon2id$v=19$m=19456,t=2,p=1$EWckzuHwNMK8tu506u6Hbg$hWf1t6F/BQKMXkH41VWlrktCFiu7REqH3i7n3BV5sOc');

Now start the server with cargo run and log in with curl, asking it to save the cookie the server sets:

curl -i -c cookies.txt -X POST http://127.0.0.1:3000/login -H 'Content-Type: application/json' -d '{"email":"ada@example.com","password":"test-password-123"}'

The response is:

HTTP/1.1 200 OK
content-type: application/json
set-cookie: id=FGlsuTzUwn7KwnU10ZRweg; HttpOnly; SameSite=Strict; Path=/; Max-Age=604800
content-length: 47

{"id":1,"name":"Ada","email":"ada@example.com"}

That Set-Cookie header is the whole point of this page. The server answered the login with a cookie, and the browser or curl will send it back on later requests. The cookie file now holds the id, and the session store holds the user id under that id.

Working Setup:

If the login answers 200 and the response carries a Set-Cookie header starting with id=, the session was stored. The exact id is different on every login, because a fresh session id is generated each time. What matters is the shape: a short random id, HttpOnly, SameSite=Strict, Path=/, and a Max-Age of 604800 seconds, which is seven days.

The Login Steps in Order

Login is a sequence where each step depends on the one before it. The handler cannot check a password before it has the stored hash, and it cannot store the user id before the password checks out.

1

Step 1: Find the user by email

The handler queries the users table for the submitted email. fetch_optional returns Some(row) when a user exists and None when no row matches. A database failure at this point is a server problem, so it maps to InternalError and status 500.

let row = sqlx::query_as::<_, LoginRow>(
    "SELECT id, password_hash FROM users WHERE email = $1",
)
.bind(&input.email)
.fetch_optional(&pool)
.await
.map_err(|_| AppError::InternalError)?;
2

Step 2: Check the password against the stored hash

password_matches parses the stored PHC string back into its parts and runs argon2 over the submitted password with the same parameters and salt. If the result matches the stored hash, the password is correct. A hash that cannot be parsed returns false, which is treated exactly like a wrong password.

fn password_matches(password: &str, stored_hash: &str) -> bool {
    let parsed = match PasswordHash::new(stored_hash) {
        Ok(parsed) => parsed,
        Err(_) => return false,
    };
    Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok()
}
3

Step 3: Refuse with one generic answer on any failure

A missing user, a user with no hash, and a wrong password all return the same AppError::Unauthorized. The client sees status 401 and the body {"error":"unauthorized"} in every case, and cannot tell which of the three happened. That sameness is deliberate: different answers would let an attacker probe which emails have accounts.

let user_id = match row {
    Some(row) => match row.password_hash {
        Some(hash) if password_matches(&input.password, &hash) => row.id,
        _ => return Err(AppError::Unauthorized),
    },
    None => return Err(AppError::Unauthorized),
};
4

Step 4: Store the user id in the session

session.insert("user_id", user_id) writes the id under the key "user_id". The value is an i32, a 32-bit integer, which is the type of the id column. The insert is async and returns a Result, so a store failure maps to InternalError. Nothing about the user except the id goes into the session.

session
    .insert("user_id", user_id)
    .await
    .map_err(|_| AppError::InternalError)?;
5

Step 5: Give the session a fresh id

session.cycle_id() replaces the session id with a new one while keeping the stored data. The session the visitor arrived with was anonymous, created before login. Giving it a fresh id after login means an id someone may have seen before the login cannot be used to ride along on the new login. That attack is called session fixation, and cycling the id at login is the standard defence against it.

session
    .cycle_id()
    .await
    .map_err(|_| AppError::InternalError)?;
6

Step 6: Return the user

The handler reads the user row back by id and returns it as JSON. The response body holds the id, the name, and the email. It holds no password and no hash. The session cookie travels in the response header, not in the body, which keeps the two apart: the body is data for the client to display, and the header is the ticket for the next request.

let user = sqlx::query_as::<_, User>(
    "SELECT id, name, email FROM users WHERE id = $1",
)
.bind(user_id)
.fetch_one(&pool)
.await
.map_err(|_| AppError::InternalError)?;

Ok(Json(user))

The login response sets one cookie. Read it piece by piece, because each piece teaches something about the design:

set-cookie: id=FGlsuTzUwn7KwnU10ZRweg; HttpOnly; SameSite=Strict; Path=/; Max-Age=604800

The name is id, which is the layer's default cookie name. The value, FGlsuTzUwn7KwnU10ZRweg, is a random session id generated by the crate. It is not the user id, not the email, and not any part of the password. It is an opaque pointer: it means nothing on its own, and it only gains meaning when the server looks it up in the store. HttpOnly means JavaScript in the browser cannot read the cookie, which keeps a script injected into a page from stealing it. SameSite=Strict means the browser only sends it on requests that start on this site. Path=/ means it is sent on every path. Max-Age=604800 is the lifetime in seconds, seven days, which comes from the OnInactivity(Duration::days(7)) expiry set on the layer.

What the cookie does not hold is the point. It does not hold the user id. It does not hold the name or the email. It does not hold the password or the hash. All of that stays on the server: the user id in the session store, the hash in the database. If someone copies the cookie, they hold a pointer to a session, and the server can end that session in one place. If the user id itself travelled in the cookie, anyone could edit it and become another user, which is exactly the attack the session design prevents.

Never put the user id in the cookie yourself:

It is tempting to skip the session and set a cookie like user_id=1 directly. That cookie is a claim the client makes about who they are, and the server has no way to know whether the claim is true. Anyone can change the 1 to a 2. The session cookie works because the claim lives on the server, under an id the client cannot forge into a different user. The wrong version of this mistake, with its fix, is shown in the mistakes section below.

Why Only the Id Goes Into the Session

Three reasons decide what gets stored, and all three point at the id alone. The first is size. The session record is loaded from the store on every request, so everything in it is read on every request. An id is four bytes. A whole user row with a name, an email, and whatever else the table grows is larger, and the cost is paid on every request for no benefit.

The second is freshness. Data copied into the session freezes at login time. If the user changes their name, the copy in the session still shows the old name until the next login. An id never goes stale: the handler looks the user up by id when it needs current data, and the database is always the fresh copy.

The third is secrecy. The session store is server-side, but it is still storage, and storage can be read by backups, by logs, and by anyone with database access. An id reveals nothing about the user on its own. A password hash, an email, or a permission list in the session would each widen what a leak exposes. The rule is simple to remember: the session holds the smallest fact that identifies the user, and the database holds everything else.

A Richer Example - Validation and a Login Count

The smallest version trusts the input and stores one value. A richer login does two more things: it rejects empty fields before touching the database, and it keeps a count of how many times this session has logged in, which shows that a session can hold more than one value and that a handler can read a value before writing it.

src/lib.rs
async fn login(
    State(pool): State<PgPool>,
    session: Session,
    Json(input): Json<LoginInput>,
) -> HandlerResult<Json<serde_json::Value>> {
    if input.email.trim().is_empty() || input.password.is_empty() {
        return Err(AppError::ValidationError(
            "email and password are required".to_string(),
        ));
    }

    let row = sqlx::query_as::<_, LoginRow>(
        "SELECT id, password_hash FROM users WHERE email = $1",
    )
    .bind(&input.email)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    let user_id = match row {
        Some(row) => match row.password_hash {
            Some(hash) if password_matches(&input.password, &hash) => row.id,
            _ => return Err(AppError::Unauthorized),
        },
        None => return Err(AppError::Unauthorized),
    };

    let logins: i32 = session
        .get("login_count")
        .await
        .map_err(|_| AppError::InternalError)?
        .unwrap_or(0);
    session
        .insert("user_id", user_id)
        .await
        .map_err(|_| AppError::InternalError)?;
    session
        .insert("login_count", logins + 1)
        .await
        .map_err(|_| AppError::InternalError)?;

    Ok(Json(serde_json::json!({ "id": user_id, "logins": logins + 1 })))
}

The empty-field check runs first and returns ValidationError, which maps to status 422 with the message in the body. A 422 means the request was well formed but the values in it failed validation. Checking before the query saves a database round trip for input that can never succeed, and it gives the client a clearer error than a 401 would. The trim on the email removes leading and trailing spaces before the check, so an email of only spaces counts as empty.

The login count shows the read-then-write shape. session.get("login_count") returns an Option<i32>, and unwrap_or(0) turns a missing count into zero on the first login. The handler then inserts the user id and the count plus one. Both inserts happen before the response, and the layer saves them together at the end of the request. The response body reports the count, so logging in twice with the same cookie shows {"id":1,"logins":1} and then {"id":1,"logins":2}.

A missing value is normal, not an error:

get returning None is the ordinary case for a key that was never stored, and unwrap_or is the usual way to supply a starting value. Reserve the error arm for a real store failure or a value stored under the wrong type. Treating a missing key as an error would turn every first visit into a 500.

What Happens When the Password Hash Is Missing

The password_hash column is nullable, and a NULL there means the user has no password login. That happens for users created by other means, such as an admin creating an account before the user sets a password, or an account that signs in through an external provider. The login code handles it in the match on row.password_hash: the None arm falls into the same _ branch as a wrong password and returns the generic 401.

That sameness matters. If a missing hash returned a different error, such as a 422 saying the account has no password, an attacker could use the difference to learn which accounts have passwords set. The generic 401 keeps all three failures indistinguishable, and the user with no hash simply cannot log in with a password, which is the correct outcome. Setting a password for that user is a different operation, and it belongs to the signup flow, not to login.

The Login Request Flow

The full path of a login request, from the browser to the database and back, looks like this:

Browser posts email and password to /login
        |
        v
Session layer loads the session from the cookie, or starts an empty one
        |
        v
Handler looks up the user by email
        |
        v
Argon2 checks the password against the stored hash
        |
        v
Handler inserts user_id into the session and cycles the id
        |
        v
Layer saves the session and sets the cookie in the response
        |
        v
Browser stores the cookie and sends it on the next request

The session layer runs twice around the handler: once before, to load the session, and once after, to save it. The handler itself only does the middle three steps. That split is why the handler code stays short: loading, saving, and cookie handling are the layer's job, and the handler only decides what goes into the session.

Testing It

Two tests cover the behaviour that matters: a correct login sets a cookie, and a wrong password does not. The tests send mock requests straight through the router with oneshot, so no server needs to run. Add the tower crate as a development dependency:

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
tests/session_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode, header},
};
use axum_project::app;
use serde_json::json;
use sqlx::PgPool;
use tower::ServiceExt;

const DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_sessions";

async fn pool() -> PgPool {
    PgPool::connect(DATABASE_URL).await.unwrap()
}

#[tokio::test]
async fn login_ok_sets_a_session_cookie() {
    let response = app(pool().await)
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/login")
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(
                    json!({"email": "ada@example.com", "password": "test-password-123"})
                        .to_string(),
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let set_cookie = response
        .headers()
        .get(header::SET_COOKIE)
        .expect("login sets a cookie")
        .to_str()
        .unwrap()
        .to_string();
    assert!(set_cookie.starts_with("id="), "{set_cookie}");
    assert!(set_cookie.contains("HttpOnly"), "{set_cookie}");
    assert!(!set_cookie.contains("Secure"), "{set_cookie}");
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        body.as_ref(),
        b"{\"id\":1,\"name\":\"Ada\",\"email\":\"ada@example.com\"}"
    );
}

#[tokio::test]
async fn login_with_wrong_password_is_401() {
    let response = app(pool().await)
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/login")
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(
                    json!({"email": "ada@example.com", "password": "wrong-password"})
                        .to_string(),
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert!(response.headers().get(header::SET_COOKIE).is_none());
}

The first test logs in with the seeded user and checks three things: the status is 200, the Set-Cookie header starts with id= and carries HttpOnly without Secure, and the body is the user JSON. The Secure check is there because this project runs over plain HTTP locally, where a Secure cookie would never come back. The second test logs in with a wrong password and checks two things: the status is 401, and no Set-Cookie header is present at all. A failed login must not set a cookie, because a cookie from a failed login would be a session that was never earned. Run both with cargo test.

What the tests prove:

Together the two tests pin down the contract of this page: success sets exactly one session cookie, failure sets none. If a later change to the handler broke either half, the tests would catch it before the server ever ran.

Common Beginner Mistakes

Trusting a user id sent by the client

// Wrong - the client claims to be user 1, and nothing checks the claim
#[derive(Debug, Deserialize)]
struct LoginInput {
    user_id: i32,
}

async fn login(
    session: Session,
    Json(input): Json<LoginInput>,
) -> HandlerResult<Json<serde_json::Value>> {
    session
        .insert("user_id", input.user_id)
        .await
        .map_err(|_| AppError::InternalError)?;
    Ok(Json(json!({ "id": input.user_id })))
}

This handler stores whatever id the client sends, with no password anywhere. Anyone can post {"user_id": 2} and become user 2. The fix is the version at the top of this page: look the user up by email, check the password against the stored hash, and store the id that came from the database, never the id that came from the request. The rule is that the server decides who the visitor is, and the visitor's only input to that decision is the password.

The client never decides who it is:

Any value that arrives in a request body, a header, or a query string is a claim, not a fact. The server may use the claim to look something up, as it uses the email to find the user, but it must never accept the claim itself as proof. The session exists precisely so that proof, once established by the password check, is remembered on the server side.

Storing the password in the session

// Wrong - the password does not belong in the session
session.insert("password", input.password).await.unwrap();

The password was needed for one check, and the check is over. Storing it keeps a secret in the session store for the whole lifetime of the session, where it can leak through a backup or a store inspection, and it buys nothing: no later step needs the password again. Store the user id. If a later step needs to re-check the password, such as changing the password itself, ask the visitor to type it again at that moment.

Returning different errors for different failures

// Wrong - the two answers let an attacker probe which emails exist
let user_id = match row {
    Some(row) => match row.password_hash {
        Some(hash) if password_matches(&input.password, &hash) => row.id,
        Some(_) => return Err(AppError::ValidationError("wrong password".to_string())),
        None => return Err(AppError::ValidationError("no password set".to_string())),
    },
    None => return Err(AppError::NotFound),
};

Three different answers, three different leaks: a 404 says the email has no account, a "wrong password" says the account exists, and a "no password set" says how the account signs in. The fix is the single generic 401 for all three cases, which is what the handler at the top of this page returns. The visitor who mistyped their own password loses nothing from the generic answer, because the login form already tells them the combination was wrong.

Forgetting to await the insert

// Wrong - the future is created and dropped, and nothing is stored
session.insert("user_id", user_id);

insert is async, so calling it without .await builds a future and drops it without running it. The compiler warns about the unused future, but the program still compiles, and the login then answers 200 without setting anything in the session. The next request finds an empty session. The fix is .await, and the compiler warning is the signal: never ignore an unused-future warning on a session call.

A dropped future stores nothing:

An insert without .await fails silently: the login still returns 200, the cookie is still set, and the session is still empty. The only sign is the compiler warning about an unused future. Treat that warning as an error on any session call, because a login that looks successful and stores nothing is harder to debug than one that fails loudly.

Final Complete Example

Here is everything from this page in one place: the error type, the login handler, the session layer, and the entry point that runs the migrations and serves the router.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("resource not found")]
    NotFound,
    #[error("{0}")]
    ValidationError(String),
    #[error("something went wrong")]
    InternalError,
    #[error("unauthorized")]
    Unauthorized,
    #[error("forbidden")]
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound => StatusCode::NOT_FOUND,
            AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
            AppError::Unauthorized => StatusCode::UNAUTHORIZED,
            AppError::Forbidden => StatusCode::FORBIDDEN,
        };
        let body = Json(json!({ "error": self.to_string() }));
        (status, body).into_response()
    }
}

pub type HandlerResult<T> = Result<T, AppError>;
src/lib.rs
pub mod errors;

use argon2::{
    Argon2,
    password_hash::{PasswordHash, PasswordVerifier},
};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use errors::{AppError, HandlerResult};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};
use time::Duration;

#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginInput {
    pub email: String,
    pub password: String,
}

#[derive(Debug, sqlx::FromRow)]
struct LoginRow {
    id: i32,
    password_hash: Option<String>,
}

pub fn app(pool: PgPool) -> Router {
    let session_store = MemoryStore::default();
    let session_layer = SessionManagerLayer::new(session_store)
        .with_secure(false)
        .with_expiry(Expiry::OnInactivity(Duration::days(7)));

    Router::new()
        .route("/login", post(login))
        .route("/public", get(public))
        .layer(session_layer)
        .with_state(pool)
}

async fn public() -> &'static str {
    "Anyone can read this."
}

fn password_matches(password: &str, stored_hash: &str) -> bool {
    let parsed = match PasswordHash::new(stored_hash) {
        Ok(parsed) => parsed,
        Err(_) => return false,
    };
    Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok()
}

async fn login(
    State(pool): State<PgPool>,
    session: Session,
    Json(input): Json<LoginInput>,
) -> HandlerResult<Json<User>> {
    let row = sqlx::query_as::<_, LoginRow>(
        "SELECT id, password_hash FROM users WHERE email = $1",
    )
    .bind(&input.email)
    .fetch_optional(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    let user_id = match row {
        Some(row) => match row.password_hash {
            Some(hash) if password_matches(&input.password, &hash) => row.id,
            _ => return Err(AppError::Unauthorized),
        },
        None => return Err(AppError::Unauthorized),
    };

    session
        .insert("user_id", user_id)
        .await
        .map_err(|_| AppError::InternalError)?;
    session
        .cycle_id()
        .await
        .map_err(|_| AppError::InternalError)?;

    let user = sqlx::query_as::<_, User>(
        "SELECT id, name, email FROM users WHERE id = $1",
    )
    .bind(user_id)
    .fetch_one(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;

    Ok(Json(user))
}
src/main.rs
use axum_project::app;
use sqlx::PgPool;

#[tokio::main]
async fn main() {
    let pool = PgPool::connect("postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_sessions")
        .await
        .unwrap();
    sqlx::migrate!("./migrations").run(&pool).await.unwrap();

    let app = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run it with cargo run, log in with curl, and watch for the Set-Cookie header. That header is the proof that the login worked the way this page describes: the password was checked once, the id was stored on the server, and the client carries only a ticket.

Summary

Login ends where the session begins. The password check answers a question about this one request, and the insert turns that answer into something the next request can use without asking again. The single most important insight is the split between what is checked and what is stored: the password is checked and then forgotten, the user id is stored and then trusted, and the cookie carries neither one. It carries only a random id that points at the stored record. That split decides what goes where in every handler that follows: secrets are checked at the door and never stored, the id is stored and never taken from the client, and failures all sound the same. A login that follows those three rules is a login the rest of the application can build on without re-checking anything.