actix-web
actix-web copied to clipboard
Can't set a signed cookie or a CookieJar
~Your issue may already be reported! Please search on the Actix Web issue tracker before creating one.~ Searched ✔️
Expected Behavior
be able to set a signed cookie.
Current Behavior
When trying to set a cookie (using res_builder.cookie(...)
) it always uses CookieJar::new()
(from source) leaving the user unable to set anything differently. When using actix-identity
or actix-session
it allows setting a signed cookie, but it might be too much of a stretch just to set a single cookie.
Possible Solution
- Add a method to get/set cookie jar. To be able to use a
SignedJar
for instance. Or - Add a method to add signed cookies using a configuration. Just like
QueryConfig
does.
Context
I was trying to set a trivial cookie that I don't want the end user to be able to modify it, but ended up using a lot of time trying, reading, and it ended up being way harder than I think it should be.
Your Environment
actix = "0.10"
actix-web = "3.3"
actix-web-actors = "3.0"
actix-identity = "0.3"
- Rust Version (I.e, output of
rustc -V
):rustc 1.56.1 (59eed8a2a 2021-11-01)
- Actix Web Version:
3.3.2
PS: This is my first time using actix-web
so if there was something that I missed please advise.
I like this idea but it's going to take a bit of thinking about a nice API for it so I'm pushing it back for now.
In the mean time here's (verbose) a way to do it.
// Secret is SHA-256 hash of 'Super secret!' passed through HKDF-SHA256.
let key = actix_web::cookie::Key::from(&[
89, 202, 200, 125, 230, 90, 197, 245, 166, 249, 34, 169, 135, 31, 20, 197, 94, 154,
254, 79, 60, 26, 8, 143, 254, 24, 116, 138, 92, 225, 159, 60, 157, 41, 135, 129, 31,
226, 196, 16, 198, 168, 134, 4, 42, 1, 196, 24, 57, 103, 241, 147, 201, 185, 233, 10,
180, 170, 187, 89, 252, 137, 110, 107,
]);
let mut jar = CookieJar::new();
let mut signed_jar = jar.signed_mut(&key);
let cookie = actix_web::cookie::Cookie::new("foo", "baz");
signed_jar.add(cookie);
let cookie = jar.get("foo").unwrap().clone();
let res = HttpResponse::Ok().cookie(cookie).finish();
println!("{:?}", res.headers().get("set-cookie"));
// prints: Some("foo=+CudKhBD9+eyPnLkKhfFmYuLkJSno4my5786xCPsfaM=baz")
Hey @robjtede, yeah, ended using something really similar in verbosity, but an API to do it directly would be great!