FAQ - Help and questions

How do I set, read and delete cookies in axum?

#axum#cookies#axum-extra#securitypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

With the axum-extra cookie feature, take a CookieJar as an argument, read with jar.get, and return (jar.add(cookie), body) to send Set-Cookie. Set HttpOnly, Secure and SameSite on cookies you do not need in JavaScript, and delete with jar.remove using the same path as when it was set.

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, time 0.3

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

#1

Answer#

CookieJar from axum-extra reads the Cookie request header and collects the Set-Cookie headers to send back. Return the jar with the response, or the cookie is not sent.

src/main.rsrust
use axum::{body::{to_bytes, Body}, http::{header, Request}, routing::get, Router};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use time::Duration;
use tower::ServiceExt;

async fn theme(jar: CookieJar) -> (CookieJar, String) {
    let current = jar.get("theme").map(|c| c.value().to_string()).unwrap_or_else(|| "light".into());
    let cookie = Cookie::build(("theme", "dark"))
        .path("/")
        .http_only(true)
        .secure(true)
        .same_site(SameSite::Lax)
        .max_age(Duration::days(30));
    (jar.add(cookie), format!("theme was {current}, now dark"))
}

async fn reset(jar: CookieJar) -> CookieJar {
    jar.remove(Cookie::build("theme").path("/")) // must use the same path as when it was set
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/theme", get(theme)).route("/reset", get(reset));
    for (uri, cookie) in [("/theme", None), ("/theme", Some("theme=dark; other=1")), ("/reset", Some("theme=dark"))] {
        let mut b = Request::get(uri);
        if let Some(c) = cookie { b = b.header(header::COOKIE, c); }
        let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
        let set: Vec<_> = res.headers().get_all(header::SET_COOKIE).iter().map(|v| v.to_str().unwrap().to_string()).collect();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{uri} (Cookie: {cookie:?}) -> {:?}\n  Set-Cookie: {set:?}", String::from_utf8_lossy(&body));
    }
}
text
/theme (Cookie: None) -> "theme was light, now dark"
  Set-Cookie: ["theme=dark; HttpOnly; SameSite=Lax; Secure; Path=/; Max-Age=2592000"]
/theme (Cookie: Some("theme=dark; other=1")) -> "theme was dark, now dark"
  Set-Cookie: ["theme=dark; HttpOnly; SameSite=Lax; Secure; Path=/; Max-Age=2592000"]
/reset (Cookie: Some("theme=dark")) -> ""
  Set-Cookie: ["theme=; Path=/; Max-Age=0; Expires=Fri, 05 Dec 2025 09:02:58 GMT"]

The attributes in the first Set-Cookie line:

  • HttpOnly: page scripts cannot read the cookie.
  • Secure: the browser sends it only over HTTPS.
  • SameSite=Lax: the browser does not send it on most cross-site sub-requests.
  • Path=/ and Max-Age: where it applies and for how long.

The reset call produced theme=; Path=/; Max-Age=0; ..., which tells the browser to drop the cookie. In this run a removal was only emitted when the request carried the cookie (a /reset without a Cookie header produced no Set-Cookie line).

Cargo.tomltoml
axum-extra = { version = "0.10.3", features = ["cookie"] }
time = "0.3"

Common mistakes#

  • Forgetting to return the jar: the handler changes it, but nothing is sent.
  • Removing a cookie with a different Path than the one it was set with. The browser treats them as different cookies.
  • Storing secrets or permissions in a cookie value the user can edit. Keep data on the server and store only an identifier (see the thread on sessions).

Can the browser store cookies on plain http during development?#

A cookie with Secure may be ignored on a plain http address by the browser. Test the final settings over HTTPS, and check your browser's current rules for localhost.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet