pub struct Cookies { /* private fields */ }Expand description
Parse request cookies and serialize response cookies.
A bidirectional middleware that parses the cookie header of an incoming
request and extends the request’s cookie jar with the extracted cookies,
then calls next to obtain a response and serializes any modified cookies
into Set-Cookie headers.
§Example
use cookie::{Cookie, SameSite};
use std::process::ExitCode;
use via::{Cookies, Error, Next, Request, Response, Server};
async fn greet(request: Request, _: Next) -> via::Result {
use time::Duration;
let head = request.envelope();
// `should_set_name` indicates whether "name" was sourced from the
// request URI. When false, the "name" cookie should not be modified.
//
// `name` is a Cow that contains either the percent-decoded value of
// the "name" cookie or the percent-decoded value of the "name"
// parameter in the request URI.
let (should_set_name, name) = match head.cookies().get("name") {
Some(cookie) => (false, cookie.value().into()),
None => (true, head.param("name").decode().into_result()?),
};
// Build the greeting response using a reference to name.
let mut response = Response::build().text(format!("Hello, {}!", name.as_ref()))?;
// If "name" came from the request uri, set the "name" cookie.
if should_set_name {
response.cookies_mut().add(
Cookie::build(("name", name.into_owned()))
.http_only(true)
.max_age(Duration::hours(1))
.path("/")
.same_site(SameSite::Strict)
.secure(true),
);
}
Ok(response)
}
#[tokio::main]
async fn main() -> Result<ExitCode, Error> {
let mut app = via::app(());
// Provide cookie support for downstream middleware.
app.uses(Cookies::new().allow("name").decode());
// Respond with a greeting when a user visits /hello/:name.
app.route("/hello/:name").to(via::get(greet));
// Start serving our application from http://localhost:8080/.
Server::new(app).listen(("127.0.0.1", 8080)).await
}§Errors
The Cookies middleware responds with a 500 error if any of the following
conditions are met:
- A Set-Cookie header cannot be constructed
- The maximum capacity of the response header map is exceeded
§Security
In production, we recommend using either a
SignedJar
or
PrivateJar
to store security sensitive cookies.
A signed jar signs all cookies added to it and verifies cookies retrieved from it, preventing clients from tampering with or fabricating cookie data. A private jar both signs and encrypts cookies, providing all the guarantees of a signed jar while also ensuring confidentiality.
§Best Practices
As a best practice, in order to mitigate the vast majority of security
related concerns of shared state with a client via cookies–we recommend
setting HttpOnly, Max-Age, SameSite=Strict, and Secure for every
cookie used by your application.
-
HttpOnly
Prevents client-side scripts from accessing the cookie, mitigating cross- site scripting (XSS) attacks. This should be enabled for any cookie that does not need to be accessed directly from JavaScript. Requests made from JavaScript using the Fetch API withcredentials: "include"or"same-origin"automatically include all relevant cookies for the request’s origin, including those marked asHttpOnly. -
Max-Age
Limits how long the browser will store and send the cookie. This reduces the window in which a leaked or stolen cookie can be used, and helps prevent session accumulation on the client. -
SameSite=Strict
Restricts cookies to same-site requests, mitigating CSRF attacks. If the cookie does not need to be shared cross-site, this setting practically eliminates CSRF risk in modern browsers. However, it prevents authentication flows that involve redirects from external identity providers (OAuth, SAML, etc.). -
Secure
Instructs the client to only include the cookie in requests made using thehttps:scheme or tolocalhost.
use cookie::{Cookie, Key, SameSite};
use http::StatusCode;
use serde::Deserialize;
use std::process::ExitCode;
use via::{Cookies, Error, Next, Payload, Request, Response, Server};
#[derive(Deserialize)]
struct Login {
username: String,
password: String,
}
struct Unicorn {
secret: Key,
}
async fn login(request: Request<Unicorn>, _: Next<Unicorn>) -> via::Result {
use time::Duration;
let (body, app) = request.into_future();
let params = body.await?.json::<Login>()?;
// Insert username and password verification here...
// For now, we'll just assert that the password is not empty.
if params.password.is_empty() {
via::raise!(401, message = "Invalid username or password.");
}
// Generate a response with no content.
//
// If we were verifying that a user with the provided username and
// password exists in a database table, we'd probably respond with the
// matching row as JSON.
let mut response = Response::build().status(204).finish()?;
// Add our session cookie that contains the username of the active user
// to our private cookie jar. The value of the cookie will be signed
// and encrypted before it is included as a set-cookie header.
response.cookies_mut().private_mut(&app.secret).add(
Cookie::build(("via-session", params.username))
.http_only(true)
.max_age(Duration::hours(1))
.path("/")
.same_site(SameSite::Strict)
.secure(true),
);
Ok(response)
}
#[tokio::main]
async fn main() -> Result<ExitCode, Error> {
let mut app = via::app(Unicorn {
secret: std::env::var("VIA_SECRET_KEY")
.map(|secret| secret.as_bytes().try_into())
.expect("missing required env var: VIA_SECRET_KEY")
.expect("unexpected end of input while parsing VIA_SECRET_KEY"),
});
// Unencoded cookie support.
app.uses(Cookies::new().allow("via-session"));
// Add our login route to our application.
app.route("/auth/login").to(via::post(login));
// Start serving our application from http://localhost:8080/.
Server::new(app).listen(("127.0.0.1", 8080)).await
}Implementations§
Source§impl Cookies
impl Cookies
Sourcepub fn new() -> Self
pub fn new() -> Self
Returns middleware that provides support for unencoded request and response cookies.
§Example
app.uses(Cookies::new());Sourcepub fn allow(self, name: impl AsRef<str>) -> Self
pub fn allow(self, name: impl AsRef<str>) -> Self
Add the provided cookie name to the allow list.
By default, the Cookies middleware ignores cookies with names that are not explicitly allowed. This filters out irrelevant cookies and keeps the number of cookies in the request and response cookie jars bounded.
§Example
app.uses(Cookies::new().allow("via-session"));