Session-based auth

Learn what session-based auth is, how a cookie holding only a session id works, and when sessions fit your Axum app

Session-based auth is a way for a server to remember that a user has logged in. After the user proves who they are once, usually with an email and a password, the server creates a record called a session. A session is a small piece of memory on the server that says "this login happened, and it belongs to this user". On every request after that, the browser sends back a short random string called a session id, and the server looks that id up in its own memory to find out who is asking.

Where This Fits

Every web app that has accounts needs an answer to one question: after the user logs in, how does the server know it is still the same user on the next request? HTTP, the protocol browsers and servers use to talk, does not remember anything between requests. Each request arrives on its own, with no memory of the one before it. Session-based auth is the oldest and most direct answer to that question: the server keeps the memory itself, and the browser only carries the key to it.

Think of it like a coat check. You hand over your coat, the attendant gives you a numbered ticket, and the coat stays on the rack. The ticket is useless on its own - it holds no coat, no name, no address. It only works because the attendant can match the number to the rack. A session id works the same way: the browser holds the ticket, the server holds the coat.

The Smallest Working Version

Here is the smallest session-based login you can run. It uses two files: src/lib.rs holds the app function with the routes, and src/main.rs starts the server. The session store is an in-memory HashMap kept inside shared app state. A HashMap is a Rust collection that maps one value to another, like a dictionary. Shared app state means data the whole app can reach, passed into handlers with the State extractor.

src/lib.rs
use axum::{
    Json, Router,
    extract::State,
    http::{HeaderMap, StatusCode, header},
    response::IntoResponse,
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

#[derive(Clone)]
pub struct AppState {
    pub sessions: Arc<Mutex<HashMap<String, i32>>>,
}

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

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

pub fn app() -> Router {
    let state = AppState {
        sessions: Arc::new(Mutex::new(HashMap::new())),
    };
    Router::new()
        .route("/login", post(login))
        .route("/profile", get(profile))
        .with_state(state)
}

async fn login(
    State(state): State<AppState>,
    Json(form): Json<LoginForm>,
) -> Result<impl IntoResponse, StatusCode> {
    if form.email != "ada@example.com" || form.password != "secret123" {
        return Err(StatusCode::UNAUTHORIZED);
    }
    let session_id = uuid::Uuid::new_v4().to_string();
    state
        .sessions
        .lock()
        .unwrap()
        .insert(session_id.clone(), 1);
    let mut headers = HeaderMap::new();
    headers.insert(
        header::SET_COOKIE,
        format!("session_id={}; HttpOnly; Path=/", session_id)
            .parse()
            .unwrap(),
    );
    Ok((headers, Json(serde_json::json!({ "message": "logged in" }))))
}

async fn profile(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<Json<User>, StatusCode> {
    let cookie = headers
        .get(header::COOKIE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or("");
    let session_id = cookie
        .split(';')
        .map(str::trim)
        .find_map(|part| part.strip_prefix("session_id="));
    let user_id = match session_id {
        Some(id) => state.sessions.lock().unwrap().get(id).copied(),
        None => None,
    };
    match user_id {
        Some(1) => Ok(Json(User {
            id: 1,
            name: "Ada".to_string(),
            email: "ada@example.com".to_string(),
        })),
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}
src/main.rs
use axum_project::app;

#[tokio::main]
async fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The Cargo.toml file needs these dependencies:

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

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
uuid = { version = "1", features = ["v4"] }

Run it with cargo run, then log in from a second terminal:

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

The -i flag tells curl to print the response headers as well as the body. You will see a header like this in the output:

set-cookie: session_id=3f8a2c1e-9b4d-4a7e-8c1f-2e6b5d4a3c9f; HttpOnly; Path=/

That header is the server handing the browser its coat-check ticket. Copy the session id value, then ask for the profile with it:

curl http://127.0.0.1:3000/profile \
  -H "Cookie: session_id=3f8a2c1e-9b4d-4a7e-8c1f-2e6b5d4a3c9f"

The server answers with the user it found in its own memory:

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

Ask for the profile without any cookie and the answer changes:

curl -i http://127.0.0.1:3000/profile
HTTP/1.1 401 Unauthorized

A 401 status means the server does not know who is asking. The retry test makes the meaning concrete: if logging in again could fix the request, the answer is 401. Here it could, so 401 is right.

Working Setup:

If login returns a set-cookie header, the profile request with that cookie returns Ada, and the profile request without it returns 401, the session flow works end to end.

How the Login Handler Works

The login handler does four things, and the order matters. First it checks the email and password. In this small example the check is a hard-coded comparison, because this page is about sessions, not about checking passwords against a database. A real app looks the user up in its users table and compares a stored password hash. The shape of the check stays the same either way: right credentials continue, wrong credentials stop here with 401.

Second, it creates the session id with uuid::Uuid::new_v4(). A UUID is a 128-bit random value written as 36 characters with hyphens, like the one in the set-cookie header above. The v4 in the name means the value is random, not derived from anything about the user or the time. Randomness is the whole point: nobody should be able to guess another user's session id. A counter like 1, 2, 3 would be guessable, and guessing a session id is the same as stealing that login.

Third, it stores the session in the HashMap, mapping the session id to the user id 1. Notice what is stored and what is not. The map holds one number, the user id. It does not hold the name, the email, or the password. The user id is enough, because the handler can look up the rest from the users table when it needs it. Storing as little as possible in the session keeps the server memory small and keeps sensitive data out of a place it does not need to be.

Fourth, it sends the session id back in a Set-Cookie header. Set-Cookie is the response header a server uses to ask the browser to store a cookie, which is a small piece of text the browser keeps and sends back on later requests to the same site. The header in this example carries two extra flags after the value. HttpOnly tells the browser not to let JavaScript on the page read the cookie, which keeps a script injected into the page from stealing it. Path=/ tells the browser to send the cookie with requests to every path on the site, not just /login.

How the Profile Handler Reads the Session Back

The profile handler reverses the process. It reads the Cookie request header, which is what the browser sends back after storing the cookie. A browser can send several cookies at once, separated by semicolons, so the handler splits the header on ;, trims the spaces, and looks for the piece that starts with session_id=. That piece holds the ticket.

Then it looks the ticket up in the HashMap. If the map has an entry for that id, the handler knows the user id and returns that user's profile. If the map has no entry, either because the cookie is missing, the id was never issued, or the session was deleted, the handler returns 401. There is no third option and no guessing: a session id is either in the server memory or it is not.

One detail is easy to miss. The handler never trusts the cookie value itself as proof of who the user is. The cookie only says "look up this id". The server memory is what says "this id belongs to user 1". If someone forges a cookie with a random id, the lookup finds nothing and the request fails. That split between the ticket and the record is what makes the design safe.

The Cookie Is Not the Proof:

A beginner sometimes reads the session id out of the cookie and uses it directly as the user id, or stores the whole user record inside the cookie. Both break the design. The cookie holds only a random key. The server memory holds the facts. Keep those two jobs apart.

The Concept Behind Sessions

A session is server-side memory about a login. The word "session" means one stretch of activity by one user, from login until logout or expiry. The server creates that memory when the login succeeds, consults it on every request that needs to know who is asking, and deletes it when the login ends.

Three properties follow from putting the memory on the server. First, the server is the only one that can change it. The browser cannot edit its own session, because the browser only holds the id. Second, the server can end a login instantly by deleting the record, and every later request with that id fails. Third, the server knows exactly how many sessions exist and which users they belong to, because it holds the whole map.

The price of those properties is that the server has to remember something for every logged-in user. For one server and a modest number of users, a HashMap in memory is fine. For many servers behind a load balancer, which is a machine that spreads requests across several servers, an in-memory map stops working: a request can land on a different server from the one that created the session, and that server has no record of it. Real apps solve that by keeping sessions in a shared store every server can reach, such as a database. The idea does not change, only the place where the map lives.

Why This Design Fits Some Apps

Sessions fit apps where the server wants control over logins. Ending a session is one delete in the map, and the user is logged out everywhere at once. Changing what a login can do is one edit to the stored record. Nothing already handed out needs to change, because the browser holds no facts, only a key.

Sessions also fit apps where the browser should carry as little as possible. The cookie holds one short id, so it stays small even when the user record grows. A profile with a long name, a list of permissions, and a history of settings still costs the browser nothing extra, because all of that lives on the server.

The trade is that the server does a lookup on every request that needs the user. That lookup is a HashMap read, which is fast, but it is still work the server must do, and it still needs the session data to be reachable from whichever machine handles the request. Apps that want to avoid that lookup entirely use a different shape, where the client carries the facts and the server checks them instead of remembering them.

Sessions and the Users Table:

The user id stored in the session matches the id column of the users table: users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()). In this small example the handler builds the user by hand. In a real app it would use that id to fetch the row from the table.

A Richer Example With Logout and Expiry

The smallest version has two gaps a real app cannot leave open. Sessions never expire, so a stolen session id works forever. And there is no way to log out, so a session only ends when the server restarts and the HashMap is lost. This richer version closes both gaps: each session records when it was created, the profile handler rejects sessions older than 30 minutes, and a logout route deletes the session and tells the browser to throw the cookie away.

src/main.rs
use axum::{
    Json, Router,
    extract::State,
    http::{HeaderMap, StatusCode, header},
    response::IntoResponse,
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    time::{Duration, SystemTime},
};

#[derive(Clone)]
struct AppState {
    sessions: Arc<Mutex<HashMap<String, (i32, SystemTime)>>>,
}

#[derive(Deserialize)]
struct LoginForm {
    email: String,
    password: String,
}

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

const SESSION_LIFETIME: Duration = Duration::from_secs(30 * 60);

#[tokio::main]
async fn main() {
    let state = AppState {
        sessions: Arc::new(Mutex::new(HashMap::new())),
    };
    let app = Router::new()
        .route("/login", post(login))
        .route("/profile", get(profile))
        .route("/logout", post(logout))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

async fn login(
    State(state): State<AppState>,
    Json(form): Json<LoginForm>,
) -> Result<impl IntoResponse, StatusCode> {
    if form.email != "ada@example.com" || form.password != "secret123" {
        return Err(StatusCode::UNAUTHORIZED);
    }
    let session_id = uuid::Uuid::new_v4().to_string();
    state
        .sessions
        .lock()
        .unwrap()
        .insert(session_id.clone(), (1, SystemTime::now()));
    let mut headers = HeaderMap::new();
    headers.insert(
        header::SET_COOKIE,
        format!(
            "session_id={}; HttpOnly; Path=/; Max-Age={}",
            session_id,
            SESSION_LIFETIME.as_secs()
        )
        .parse()
        .unwrap(),
    );
    Ok((headers, Json(serde_json::json!({ "message": "logged in" }))))
}

fn read_session_id(headers: &HeaderMap) -> Option<String> {
    let cookie = headers
        .get(header::COOKIE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or("");
    cookie
        .split(';')
        .map(str::trim)
        .find_map(|part| part.strip_prefix("session_id="))
        .map(str::to_string)
}

fn lookup_user(state: &AppState, session_id: &str) -> Option<i32> {
    let mut sessions = state.sessions.lock().unwrap();
    let (user_id, created_at) = sessions.get(session_id)?;
    if created_at.elapsed().unwrap_or(Duration::MAX) > SESSION_LIFETIME {
        sessions.remove(session_id);
        return None;
    }
    Some(*user_id)
}

async fn profile(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<Json<User>, StatusCode> {
    let session_id = read_session_id(&headers).unwrap_or_default();
    match lookup_user(&state, &session_id) {
        Some(1) => Ok(Json(User {
            id: 1,
            name: "Ada".to_string(),
            email: "ada@example.com".to_string(),
        })),
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}

async fn logout(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> impl IntoResponse {
    if let Some(session_id) = read_session_id(&headers) {
        state.sessions.lock().unwrap().remove(&session_id);
    }
    let mut response_headers = HeaderMap::new();
    response_headers.insert(
        header::SET_COOKIE,
        "session_id=; HttpOnly; Path=/; Max-Age=0".parse().unwrap(),
    );
    (
        response_headers,
        Json(serde_json::json!({ "message": "logged out" })),
    )
}

Two changes carry the new behaviour. The map value is now a pair of the user id and the creation time, SystemTime::now() at login. SystemTime is Rust's clock reading, and elapsed() measures how much time has passed since it was taken. The lookup_user helper checks that age against the 30-minute lifetime, deletes the session when it is too old, and returns nothing, so an expired session behaves exactly like a missing one: 401.

The logout handler does two things that must happen together. It deletes the session from the map, which ends the login on the server, and it sends back a Set-Cookie header with an empty value and Max-Age=0, which tells the browser to delete the cookie at once. Doing only one half leaves the other half working: delete the map entry but keep the cookie, and the browser keeps sending a dead id; clear the cookie but keep the map entry, and anyone who copied the id can still use it.

The Max-Age flag on the login cookie is the third piece. It tells the browser how many seconds to keep the cookie, 1800 seconds here, so the browser throws it away on its own even if the user never logs out. The server-side check and the browser-side lifetime agree on 30 minutes, so neither side trusts the other to enforce the limit alone.

Try the flow with curl:

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": "secret123"}'
curl -b cookies.txt http://127.0.0.1:3000/profile
curl -i -b cookies.txt -X POST http://127.0.0.1:3000/logout
curl -i -b cookies.txt http://127.0.0.1:3000/profile

The -c cookies.txt flag saves cookies from the response into a file, and -b cookies.txt sends the saved cookies with the next request, which is how curl imitates a browser. The profile works after login, logout answers {"message":"logged out"}, and the final profile request returns 401 because the session is gone.

The login cookie in the richer example carries HttpOnly, Path=/, and Max-Age. Two more flags matter in real apps, and both are about which requests the browser attaches the cookie to. Secure tells the browser to send the cookie only over HTTPS, which is the encrypted version of HTTP. Without it, the cookie can travel over plain HTTP, where anyone on the same network can read it. Turn Secure on whenever the app runs over HTTPS, which is every app users reach on the open internet.

SameSite controls whether the browser sends the cookie on requests that start from another site, such as a link on a different page. SameSite=Lax sends it on top-level navigation, like clicking a link, but not on background requests from another site. That blocks a common attack where a malicious page triggers a request to your app in the background and rides on the victim's cookie. The default in modern browsers behaves much like Lax, but writing the flag down makes the choice visible instead of accidental.

None of these flags change what the cookie holds. They only change where it travels and who can read it. The session id stays a random key either way.

Never Put the Password in the Session:

Storing a password, a password hash, or any secret inside the session record means anyone who can read the session store learns it. The session needs exactly one fact: which user this login belongs to. The password check happens once at login and is never repeated from the session.

What Happens on Each Request

The full round trip, from the first login to a later profile request, looks like this:

Browser sends email and password to /login
        |
        v
Server checks the credentials
        |
        v
Server creates a random session id
        |
        v
Server stores session id -> user id in its memory
        |
        v
Server answers with Set-Cookie: session_id=...
        |
        v
Browser stores the cookie
        |
        v
Browser sends Cookie: session_id=... with /profile
        |
        v
Server looks the id up in its memory
        |
        v
Server finds user 1 and answers with the profile

Every step after login is a lookup, not a new check of the password. The password is checked once, at the moment the session is created. That is the whole trick of session auth: one expensive check up front, then cheap lookups for the rest of the session.

Testing the Session Flow

A test can drive the whole flow without a network connection, using tower::ServiceExt and its oneshot method, which sends one mock request straight through the Router. The test logs in, reads the set-cookie header from the response, and sends it back on a profile request, exactly like a browser would.

tests/session_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode, header},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn login_sets_cookie_and_profile_works() {
    let app = app();
    let login = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/login")
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(
                    r#"{"email":"ada@example.com","password":"secret123"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(login.status(), StatusCode::OK);
    let cookie = login
        .headers()
        .get(header::SET_COOKIE)
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    assert!(cookie.starts_with("session_id="));
    assert!(cookie.contains("HttpOnly"));
    let profile = app
        .oneshot(
            Request::builder()
                .uri("/profile")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(profile.status(), StatusCode::OK);
}

#[tokio::test]
async fn profile_without_cookie_is_401() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/profile")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

The tower crate is needed as a dev dependency:

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the tests with cargo test. The first test fails if login stops setting the cookie, if the cookie loses its HttpOnly flag, or if the profile handler stops accepting a good session. The second test guards the other side: a request with no session at all must never reach the profile. Together they pin down the exact contract of this page: login issues a ticket, the ticket opens the door, and no ticket means 401.

Common Beginner Mistakes

Using a Predictable Session Id

// Wrong - anyone can guess the next session id
let session_id = format!("session-{}", next_counter);

A counter, a timestamp, or the user id itself all fail the same way: the next value is guessable, and guessing a session id logs the attacker in as that user. Session ids must come from a random source with enough bits that guessing is hopeless. Uuid::new_v4 gives 122 random bits, which is the right shape. The fix is never to build the id from anything meaningful. Randomness is the feature.

// Wrong - the cookie now carries facts the server should hold
format!("session_id={}; HttpOnly; Path=/", serde_json::to_string(&user).unwrap())

A cookie that carries the user record can be read by anyone who sees it, and it can be edited by anyone who holds it, because the browser owns the cookie. The server has no way to know the record was changed unless it checks something else. Keep the cookie to one random id and keep the facts in server memory, where the browser cannot reach them.

Forgetting That Restarting Wipes the Sessions

An in-memory HashMap lives only as long as the process. Restart the server and every session is gone, so every user has to log in again. For a learning project that is fine, even useful, because it makes the server-side nature of sessions visible. For a real app it is a surprise users will not enjoy. The fix is to keep the session map somewhere that survives a restart, such as a database table, and the page about session storage covers that shape.

Checking the Password on Every Request

// Wrong - the session exists so the password check happens once
async fn profile(Json(form): Json<LoginForm>) -> ... {

A handler that asks for the password again on every request has thrown away the point of the session. The session is the proof that the password was already checked. If a handler needs the user, it reads the session. If a handler needs the password again, that is a different feature, usually a confirmation step before a sensitive action, and it belongs in its own handler.

Final Complete Example

Here is everything from this page in one place: login that creates a session, a profile that reads it back, logout that ends it, and a 30-minute expiry enforced on both sides.

src/main.rs
use axum::{
    Json, Router,
    extract::State,
    http::{HeaderMap, StatusCode, header},
    response::IntoResponse,
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    time::{Duration, SystemTime},
};

#[derive(Clone)]
struct AppState {
    sessions: Arc<Mutex<HashMap<String, (i32, SystemTime)>>>,
}

#[derive(Deserialize)]
struct LoginForm {
    email: String,
    password: String,
}

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

const SESSION_LIFETIME: Duration = Duration::from_secs(30 * 60);

#[tokio::main]
async fn main() {
    let state = AppState {
        sessions: Arc::new(Mutex::new(HashMap::new())),
    };
    let app = Router::new()
        .route("/login", post(login))
        .route("/profile", get(profile))
        .route("/logout", post(logout))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

async fn login(
    State(state): State<AppState>,
    Json(form): Json<LoginForm>,
) -> Result<impl IntoResponse, StatusCode> {
    if form.email != "ada@example.com" || form.password != "secret123" {
        return Err(StatusCode::UNAUTHORIZED);
    }
    let session_id = uuid::Uuid::new_v4().to_string();
    state
        .sessions
        .lock()
        .unwrap()
        .insert(session_id.clone(), (1, SystemTime::now()));
    let mut headers = HeaderMap::new();
    headers.insert(
        header::SET_COOKIE,
        format!(
            "session_id={}; HttpOnly; Path=/; Max-Age={}",
            session_id,
            SESSION_LIFETIME.as_secs()
        )
        .parse()
        .unwrap(),
    );
    Ok((headers, Json(serde_json::json!({ "message": "logged in" }))))
}

fn read_session_id(headers: &HeaderMap) -> Option<String> {
    let cookie = headers
        .get(header::COOKIE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or("");
    cookie
        .split(';')
        .map(str::trim)
        .find_map(|part| part.strip_prefix("session_id="))
        .map(str::to_string)
}

fn lookup_user(state: &AppState, session_id: &str) -> Option<i32> {
    let mut sessions = state.sessions.lock().unwrap();
    let (user_id, created_at) = sessions.get(session_id)?;
    if created_at.elapsed().unwrap_or(Duration::MAX) > SESSION_LIFETIME {
        sessions.remove(session_id);
        return None;
    }
    Some(*user_id)
}

async fn profile(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<Json<User>, StatusCode> {
    let session_id = read_session_id(&headers).unwrap_or_default();
    match lookup_user(&state, &session_id) {
        Some(1) => Ok(Json(User {
            id: 1,
            name: "Ada".to_string(),
            email: "ada@example.com".to_string(),
        })),
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}

async fn logout(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> impl IntoResponse {
    if let Some(session_id) = read_session_id(&headers) {
        state.sessions.lock().unwrap().remove(&session_id);
    }
    let mut response_headers = HeaderMap::new();
    response_headers.insert(
        header::SET_COOKIE,
        "session_id=; HttpOnly; Path=/; Max-Age=0".parse().unwrap(),
    );
    (
        response_headers,
        Json(serde_json::json!({ "message": "logged out" })),
    )
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
uuid = { version = "1", features = ["v4"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run it with cargo run and drive it with the curl commands from the richer example: login, profile, logout, profile again. The last request answers 401, which is the sound of a session ending properly.

Summary

The decision a session forces is about where the memory of a login lives, and the answer here is on the server. That one choice explains everything else on this page: the cookie holds only a random key because the facts stay behind, logout is a delete because the record is yours to remove, and expiry is a clock check because a login that never ends is a login that can be stolen forever. The mental model to keep is the coat check: the browser carries the ticket, the server keeps the coat, and the ticket is worthless without the rack behind it.

That split is also the test to apply when the next approach shows up. If the client carries the facts and the server only checks them, the trade changes shape entirely: no lookup, no shared store, and no way to end a login by deleting a record. That is the token approach, and it earns its place exactly where the server wants to stop remembering.