Struct rocket::http::CookieJar[][src]

pub struct CookieJar<'a> { /* fields omitted */ }
Expand description

Collection of one or more HTTP cookies.

CookieJar allows for retrieval of cookies from an incoming request. It also tracks modifications (additions and removals) and marks them as pending.

Pending

Changes to a CookieJar are not visible via the normal get() and get_private() methods. This is typically the desired effect as a CookieJar always reflects the cookies in an incoming request. In cases where this is not desired, the get_pending() and get_private_pending() methods are available, which always return the latest changes.

use rocket::http::{CookieJar, Cookie};

#[get("/message")]
fn message(jar: &CookieJar<'_>) {
    jar.add(Cookie::new("message", "hello!"));
    jar.add(Cookie::new("other", "bye!"));

    // `get()` does not reflect changes.
    assert!(jar.get("other").is_none());

    // `get_pending()` does.
    let other_pending = jar.get_pending("other");
    let message_pending = jar.get_pending("message");
    assert_eq!(other_pending.as_ref().map(|c| c.value()), Some("bye!"));
    assert_eq!(message_pending.as_ref().map(|c| c.value()), Some("hello!"));
}

Usage

A type of &CookieJar can be retrieved via its FromRequest implementation as a request guard or via the Request::cookies() method. Individual cookies can be retrieved via the get() and get_private() methods. Pending changes can be observed via the get_pending() and get_private_pending() methods. Cookies can be added or removed via the add(), add_private(), remove(), and remove_private() methods.

Examples

The following example shows &CookieJar being used as a request guard in a handler to retrieve the value of a “message” cookie.

use rocket::http::CookieJar;

#[get("/message")]
fn message<'a>(jar: &'a CookieJar<'_>) -> Option<&'a str> {
    jar.get("message").map(|cookie| cookie.value())
}

The following snippet shows &CookieJar being retrieved from a Request in a custom request guard implementation for User. A private cookie containing a user’s ID is retrieved. If the cookie exists and the ID parses as an integer, a User structure is validated. Otherwise, the guard forwards.

use rocket::http::Status;
use rocket::outcome::IntoOutcome;
use rocket::request::{self, Request, FromRequest};

// In practice, we'd probably fetch the user from the database.
struct User(usize);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for User {
    type Error = std::convert::Infallible;

    async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
        request.cookies()
            .get_private("user_id")
            .and_then(|c| c.value().parse().ok())
            .map(|id| User(id))
            .or_forward(())
    }
}

Private Cookies

Private cookies are just like regular cookies except that they are encrypted using authenticated encryption, a form of encryption which simultaneously provides confidentiality, integrity, and authenticity. This means that private cookies cannot be inspected, tampered with, or manufactured by clients. If you prefer, you can think of private cookies as being signed and encrypted.

Private cookies can be retrieved, added, and removed from a CookieJar collection via the get_private(), add_private(), and remove_private() methods.

Encryption Key

To encrypt private cookies, Rocket uses the 256-bit key specified in the secret_key configuration parameter. If one is not specified, Rocket will automatically generate a fresh key. Note, however, that a private cookie can only be decrypted with the same key with which it was encrypted. As such, it is important to set a secret_key configuration parameter when using private cookies so that cookies decrypt properly after an application restart. Rocket will emit a warning if an application is run in production mode without a configured secret_key.

Generating a string suitable for use as a secret_key configuration value is usually done through tools like openssl. Using openssl, for instance, a 256-bit base64 key can be generated with the command openssl rand -base64 32.

Implementations

Returns a reference to the original Cookie inside this container with the name name. If no such cookie exists, returns None.

Note: This method does not obverse changes made via additions and removals to the cookie jar. To observe those changes, use CookieJar::get_pending().

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    let cookie = jar.get("name");
}
This is supported on crate feature secrets only.

Retrives the original Cookie inside this collection with the name name and authenticates and decrypts the cookie’s value. If the cookie cannot be found, or the cookie fails to authenticate or decrypt, None is returned.

Note: This method does not obverse changes made via additions and removals to the cookie jar. To observe those changes, use CookieJar::get_private_pending().

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    let cookie = jar.get_private("name");
}

Returns a reference to the original or pending Cookie inside this container with the name name. If no such cookie exists, returns None.

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    let pending_cookie = jar.get_pending("name");
}
This is supported on crate feature secrets only.

Retrives the original or pending Cookie inside this collection with the name name and authenticates and decrypts the cookie’s value. If the cookie cannot be found, or the cookie fails to authenticate or decrypt, None is returned.

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    let pending_cookie = jar.get_private_pending("name");
}

Adds cookie to this collection.

Unless a value is set for the given property, the following defaults are set on cookie before being added to self:

  • path: "/"
  • SameSite: Strict

Example

use rocket::http::{Cookie, SameSite, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    jar.add(Cookie::new("first", "value"));

    let cookie = Cookie::build("other", "value_two")
        .path("/")
        .secure(true)
        .same_site(SameSite::Lax);

    jar.add(cookie.finish());
}
This is supported on crate feature secrets only.

Adds cookie to the collection. The cookie’s value is encrypted with authenticated encryption assuring confidentiality, integrity, and authenticity. The cookie can later be retrieved using get_private and removed using remove_private.

Unless a value is set for the given property, the following defaults are set on cookie before being added to self:

  • path: "/"
  • SameSite: Strict
  • HttpOnly: true
  • Expires: 1 week from now

These defaults ensure maximum usability and security. For additional security, you may wish to set the secure flag.

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    jar.add_private(Cookie::new("name", "value"));
}

Removes cookie from this collection and generates a “removal” cookies to send to the client on response. For correctness, cookie must contain the same path and domain as the cookie that was initially set. Failure to provide the initial path and domain will result in cookies that are not properly removed. For convenience, if a path is not set on cookie, the "/" path will automatically be set.

A “removal” cookie is a cookie that has the same name as the original cookie but has an empty value, a max-age of 0, and an expiration date far in the past.

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    jar.remove(Cookie::named("name"));
}
This is supported on crate feature secrets only.

Removes the private cookie from the collection.

For correct removal, the passed in cookie must contain the same path and domain as the cookie that was initially set. If a path is not set on cookie, the "/" path will automatically be set.

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    jar.remove_private(Cookie::named("name"));
}

Returns an iterator over all of the original cookies present in this collection.

Note: This method does not obverse changes made via additions and removals to the cookie jar.

Example

use rocket::http::{Cookie, CookieJar};

#[get("/")]
fn handler(jar: &CookieJar<'_>) {
    for c in jar.iter() {
        println!("Name: {:?}, Value: {:?}", c.name(), c.value());
    }
}

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

The associated error to be returned if derivation fails.

Derives an instance of Self from the incoming request metadata. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Converts self into T using Into<T>. Read more

Converts self into a target type. Read more

Causes self to use its Binary implementation when Debug-formatted.

Causes self to use its Display implementation when Debug-formatted. Read more

Causes self to use its LowerExp implementation when Debug-formatted. Read more

Causes self to use its LowerHex implementation when Debug-formatted. Read more

Causes self to use its Octal implementation when Debug-formatted.

Causes self to use its Pointer implementation when Debug-formatted. Read more

Causes self to use its UpperExp implementation when Debug-formatted. Read more

Causes self to use its UpperHex implementation when Debug-formatted. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

Converts self into a collection.

Pipes by value. This is generally the method you want to use. Read more

Borrows self and passes that borrow into the pipe function. Read more

Mutably borrows self and passes that borrow into the pipe function. Read more

Borrows self, then passes self.borrow() into the pipe function. Read more

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more

Borrows self, then passes self.as_ref() into the pipe function.

Mutably borrows self, then passes self.as_mut() into the pipe function. Read more

Borrows self, then passes self.deref() into the pipe function.

Mutably borrows self, then passes self.deref_mut() into the pipe function. Read more

Pipes a value into a function that cannot ordinarily be called in suffix position. Read more

Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more

Pipes a dereference into a function that cannot normally be called in suffix position. Read more

Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more

Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more

Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more

Should always be Self

Immutable access to a value. Read more

Mutable access to a value. Read more

Immutable access to the Borrow<B> of a value. Read more

Mutable access to the BorrowMut<B> of a value. Read more

Immutable access to the AsRef<R> view of a value. Read more

Mutable access to the AsMut<R> view of a value. Read more

Immutable access to the Deref::Target of a value. Read more

Mutable access to the Deref::Target of a value. Read more

Calls .tap() only in debug builds, and is erased in release builds.

Calls .tap_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref_mut() only in debug builds, and is erased in release builds. Read more

Provides immutable access for inspection. Read more

Calls tap in debug builds, and does nothing in release builds.

Provides mutable access for modification. Read more

Calls tap_mut in debug builds, and does nothing in release builds.

Provides immutable access to the reference for inspection.

Calls tap_ref in debug builds, and does nothing in release builds.

Provides mutable access to the reference for modification.

Calls tap_ref_mut in debug builds, and does nothing in release builds.

Provides immutable access to the borrow for inspection. Read more

Calls tap_borrow in debug builds, and does nothing in release builds.

Provides mutable access to the borrow for modification.

Calls tap_borrow_mut in debug builds, and does nothing in release builds. Read more

Immutably dereferences self for inspection.

Calls tap_deref in debug builds, and does nothing in release builds.

Mutably dereferences self for modification.

Calls tap_deref_mut in debug builds, and does nothing in release builds. Read more

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

Attempts to convert self into T using TryInto<T>. Read more

Attempts to convert self into a target type. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.