FAQ - Help and questions

How do server-side sessions and login cookies work in axum?

#axum#sessions#cookies#authenticationpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A session is a random identifier in an HttpOnly cookie that points to data kept on the server. At login create a new random id, store the user with an expiry, and set the cookie; at logout delete the server entry. Requests with an unknown or expired id are treated as not logged in.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; axum-extra 0.10.3, rand 0.9.5

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

The cookie holds only a random id, so the user cannot change who they are by editing it. Everything else lives in a table on the server. This program implements the whole cycle with an in-memory map:

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::{Form, State},
    http::{header, Request, StatusCode},
    routing::{get, post},
    Router,
};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use serde::Deserialize;
use std::{collections::HashMap, sync::{Arc, Mutex}, time::{Duration, Instant}};
use tower::ServiceExt;

#[derive(Clone, Default)]
struct Sessions(Arc<Mutex<HashMap<String, (String, Instant)>>>); // id -> (user, expires)

fn new_id() -> String {
    let bytes: [u8; 32] = rand::random(); // 256 random bits from the operating system's seeded generator
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

#[derive(Deserialize)]
struct Login { user: String }

async fn login(State(s): State<Sessions>, jar: CookieJar, Form(f): Form<Login>) -> (CookieJar, StatusCode) {
    let id = new_id();
    s.0.lock().unwrap().insert(id.clone(), (f.user, Instant::now() + Duration::from_secs(3600)));
    let c = Cookie::build(("sid", id)).path("/").http_only(true).same_site(SameSite::Lax);
    (jar.add(c), StatusCode::NO_CONTENT)
}

async fn me(State(s): State<Sessions>, jar: CookieJar) -> Result<String, StatusCode> {
    let id = jar.get("sid").ok_or(StatusCode::UNAUTHORIZED)?.value().to_string();
    match s.0.lock().unwrap().get(&id) {
        Some((user, expires)) if *expires > Instant::now() => Ok(format!("hello {user}")),
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}

async fn logout(State(s): State<Sessions>, jar: CookieJar) -> CookieJar {
    if let Some(c) = jar.get("sid") { s.0.lock().unwrap().remove(c.value()); } // end it on the server too
    jar.remove(Cookie::build("sid").path("/"))
}

async fn call(app: &Router, req: Request<Body>) -> (u16, Option<String>, String) {
    let res = app.clone().oneshot(req).await.unwrap();
    let status = res.status().as_u16();
    let set = res.headers().get(header::SET_COOKIE).map(|v| v.to_str().unwrap().to_string());
    let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
    (status, set, String::from_utf8_lossy(&body).into_owned())
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/login", post(login)).route("/me", get(me)).route("/logout", post(logout)).with_state(Sessions::default());
    let me_req = |sid: &str| Request::get("/me").header(header::COOKIE, format!("sid={sid}")).body(Body::empty()).unwrap();

    let req = Request::post("/login").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from("user=ada")).unwrap();
    let (_, set, _) = call(&app, req).await;
    let set = set.unwrap();
    let sid = set.split(';').next().unwrap().trim_start_matches("sid=").to_string();
    println!("Set-Cookie attributes: {}", set.split_once(';').unwrap().1.trim());
    println!("id length: {} hex characters", sid.len());
    println!("with the cookie:    {:?}", call(&app, me_req(&sid)).await);
    println!("with a guessed id:  {:?}", call(&app, me_req("0000")).await);
    let out = Request::post("/logout").header(header::COOKIE, format!("sid={sid}")).body(Body::empty()).unwrap();
    call(&app, out).await;
    println!("after logout:       {:?}", call(&app, me_req(&sid)).await);
}
text
Set-Cookie attributes: HttpOnly; SameSite=Lax; Path=/
id length: 64 hex characters
with the cookie:    (200, None, "hello ada")
with a guessed id:  (401, None, "")
after logout:       (401, None, "")

Reading the run:

  • The Set-Cookie header has HttpOnly, SameSite=Lax and Path=/.
  • The id is 64 hexadecimal characters, which is 256 random bits from rand::random, backed by rand's thread-local generator (documented as cryptographically secure and seeded by the operating system). OWASP's session management guidance asks for at least 64 bits of entropy in a session id.
  • The right id gets hello ada; a guessed id and the id after logout get 401.

What this sketch does not do#

  • Persistence. The map is lost when the program restarts and is not shared between several copies of it. Keep sessions in a database table or a shared store if either matters.
  • Cleaning. Expired entries stay in the map until someone removes them: run a periodic job (see the thread on background jobs).
  • Secure. Add .secure(true) for HTTPS sites.
  • Renewing the id at login. The sketch always creates a new id at login, which OWASP recommends after any change of privilege level.

Common mistakes#

  • Using a predictable id (a counter, a user number, a timestamp).
  • Logging out only in the browser. Remove the server entry as well, as logout does.
  • Checking a password in the same handler without hashing it (see the thread on password hashing with argon2).

Should I write this myself?#

For a real site, a maintained session library is the usual choice; the sketch shows what such a library has to do. This thread did not compile or compare any session crate.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet