SummaryWhile writing tests against endpoints that need authentication I need to add a cookie header with the session id. Is there a way to obtain the header value from a cookie jar? let jar = SignedCookieCookieJar::new();
// let session_id = "...";
// jar.add(Cookie::new("sid", session_id));
// ...
let req = Request::builder()
.method("GET")
.uri("/admin")
.header("Cookie", jar...)
.unwrap();
let res = app.oneshot(req).await.unwrap();axum versionaxum: 0.8.1, axum-extra: 0.10.0 |
Replies: 1 comment 1 reply
|
I’d generate the signed cookie via Something like: use axum::{
body::Body,
http::{header, Request},
response::IntoResponse,
};
use axum_extra::extract::cookie::{Cookie, Key, SignedCookieJar};
use tower::ServiceExt;
let key = Key::generate();
let session_id = "...";
let jar = SignedCookieJar::new(key.clone())
.add(Cookie::new("sid", session_id.to_owned()));
let res = jar.into_response();
let cookie_header = res
.headers()
.get(header::SET_COOKIE)
.unwrap()
.to_str()
.unwrap()
.split(';')
.next()
.unwrap()
.to_owned();
let req = Request::builder()
.method("GET")
.uri("/admin")
.header(header::COOKIE, cookie_header)
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();Small detail: for the request you want Also make sure the test app/router uses the same Docs: lmk if there’s a cleaner helper for this, but this works fine for tests imo 🙂 |
I’d generate the signed cookie via
SignedCookieJar, convert it into a response, then take theSet-Cookieheader and use thename=valuepart as the requestCookieheader.Something like: