How to set a Iron Cookie with an Expiration period?


#1

I know how to set a Cookie:
https://docs.rs/iron/0.5.1/iron/headers/struct.Cookie.html

It used to be possible to do it like this:

let mut cookie = CookiePair::new(String::from("session"),
                                                     session.get_id_str().to_owned());
cookie.expires = Some(time::now_utc() + CONFIG.get_session_remember());
res.headers.set(SetCookie(vec![cookie]));

Session is our own internal library.

But I upgraded to the newest version of iron(and other libraries) and now get the error:

Use of undeclared type or module `CookiePair`

Even though I am doing the same import as before:

use iron::headers::{Cookie, SetCookie, Location}

I tried importing CookiePair in hyper instead:

unresolved import `hyper::header::CookiePair`

Now when I try this:

let mut cookie = Cookie(vec![format!("session={}", session.get_id_str())]);
cookie.expires = Some(time::now_utc() + CONFIG.get_session_remember());

I get an error:
no field expires on type iron::header::Cookie

And I can’t seem to set ‘expires’ on the cookie… which being a high security website, I need. Point being… I’m trying but can’t figure this one out. Can someone please help?

Thanks!


#2

This change is probably the cause: https://github.com/hyperium/hyper/commit/f22701f7e7258ad4a26645eba47a3d374e452e86

Based on the comment there, it seems like you just add expiry information in the cookie string: https://hyper.rs/hyper/v0.10.9/hyper/header/struct.SetCookie.html


#3

Thank you very much vitalyd!!

Ok, got that much working and fixed some other things.

For future reference and people having issues:

let cookieExpireTM = time::now_utc() + CONFIG.get_session_remember();

//correct format: Expires=Wed, 09 Jun 2021 10:18:14 GMT
let cookieExpireString = cookieExpireTM.rfc822();

let mut cookie = Cookie(vec![format!("session={}", session.get_id_str()),format!("Expires={}", cookieExpireString)]);

res.headers.set(cookie);

Now the question is… how can I get the value back from the cookie? Does anyone see an easy way?

This much is at least making it past the compiler:

let cookie: Option<&Cookie> = req.headers.get();
let derefCookie = cookie.deref();

Not sure if I need deref?

derefCookie is now a “&std::vec::Vecstd::string::String” according to errors messages.

Now I guess I break apart that Vec and end up with a bunch of strings, such as:
session={session value}
expire={expire date}

Do I then have to parse the strings and find the equals sign and grab everything after the equals sign in order to finally access the actual values? Hopefully I’m making this more complicated that it is?

Wish Iron had better documentation :frowning:

Thanks again!